Skip to content

Commit

Permalink
Merge branch 'master' of git://github.com/chris-garrett/lfshook into …
Browse files Browse the repository at this point in the history
…chris-garrett-master

Conflicts:
	lfshook.go
Update README
  • Loading branch information
rifflock committed Sep 9, 2016
2 parents 9f59801 + 2b69fc4 commit 3f9d976
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
7 changes: 5 additions & 2 deletions README.md
Expand Up @@ -15,7 +15,7 @@ func NewLogger( config map[string]interface{} ) *log.Logger {
if Log != nil {
return Log
}

Log = log.New()
Log.Formatter = new(log.JSONFormatter)
Log.Hooks.Add(lfshook.NewHook(lfshook.PathMap{
Expand All @@ -26,5 +26,8 @@ func NewLogger( config map[string]interface{} ) *log.Logger {
}
```

### Formatters
lfshook will strip colors from any TextFormatter type formatters when writing to local file, because the color codes don't look so great.

### Note:
Whichever user is running the go application must have read/write permissions to the log files selected, or if the files do not yet exists, then to the directory in which the files will be created.
Whichever user is running the go application must have read/write permissions to the log files selected, or if the files do not yet exists, then to the directory in which the files will be created.
16 changes: 14 additions & 2 deletions lfshook.go
Expand Up @@ -21,6 +21,7 @@ type lfsHook struct {
paths PathMap
levels []logrus.Level
lock *sync.Mutex
formatter logrus.Formatter
}

// Given a map with keys equal to log levels.
Expand All @@ -30,13 +31,24 @@ func NewHook(levelMap PathMap) *lfsHook {
hook := &lfsHook{
paths: levelMap,
lock: new(sync.Mutex),
formatter: txtFormatter,
}
for level, _ := range levelMap {
hook.levels = append(hook.levels, level)
}
return hook
}

func (hook *lfsHook) SetFormatter(formatter logrus.Formatter) {
hook.formatter = formatter

switch hook.formatter.(type) {
case *logrus.TextFormatter:
textFormatter := hook.formatter.(*logrus.TextFormatter)
textFormatter.DisableColors = true
}
}

// Open the file, write to the file, close the file.
// Whichever user is running the function needs write permissions to the file or directory if the file does not yet exist.
func (hook *lfsHook) Fire(entry *logrus.Entry) error {
Expand All @@ -63,10 +75,10 @@ func (hook *lfsHook) Fire(entry *logrus.Entry) error {
}
defer fd.Close()

// only strip colours if we are using a TextFormatter
// only modify Formatter if we are using a TextFormatter so we can strip colors
switch entry.Logger.Formatter.(type) {
case *logrus.TextFormatter:
// swap to TextFormatter
// swap to colorless TextFormatter
formatter := entry.Logger.Formatter
entry.Logger.Formatter = txtFormatter
defer func() {
Expand Down

0 comments on commit 3f9d976

Please sign in to comment.