Skip to content

Add optional formatter to writer hook #1184

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion hooks/writer/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,29 @@ import (
)

// Hook is a hook that writes logs of specified LogLevels to specified Writer
// If Formatter is not nil, then it would used to format log entries before writing
type Hook struct {
Writer io.Writer
LogLevels []log.Level
Formatter log.Formatter
}

// Fire will be called when some logging function is called with current hook
// It will format log entry to string and write it to appropriate writer
func (hook *Hook) Fire(entry *log.Entry) error {
line, err := entry.Bytes()
var line []byte
var err error

if hook.Formatter != nil {
line, err = hook.Formatter.Format(entry)
} else {
line, err = entry.Bytes()
}

if err != nil {
return err
}

_, err = hook.Writer.Write(line)
return err
}
Expand Down
38 changes: 38 additions & 0 deletions hooks/writer/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,41 @@ func TestDifferentLevelsGoToDifferentWriters(t *testing.T) {
assert.Equal(t, a.String(), "level=warning msg=\"send to a\"\n")
assert.Equal(t, b.String(), "level=info msg=\"send to b\"\n")
}

func TestDifferentFormattersToDifferentWritter(t *testing.T) {
var a, b bytes.Buffer

log.SetOutput(ioutil.Discard) // Send all logs to nowhere by default

log.AddHook(&Hook{
Writer: &a,
LogLevels: []log.Level{
log.WarnLevel,
},
Formatter: &log.TextFormatter{
DisableTimestamp: true,
DisableColors: true,
FieldMap: log.FieldMap{
log.FieldKeyLevel: "@level",
log.FieldKeyMsg: "@message",
},
},
})
log.AddHook(&Hook{ // Send info and debug logs to stdout
Writer: &b,
LogLevels: []log.Level{
log.InfoLevel,
},
Formatter: &log.JSONFormatter{
DisableTimestamp: true,
FieldMap: log.FieldMap{
log.FieldKeyMsg: "message",
},
},
})
log.Warn("send to a")
log.Info("send to b")

assert.Equal(t, a.String(), "@level=warning @message=\"send to a\"\n")
assert.Equal(t, b.String(), "{\"level\":\"info\",\"message\":\"send to b\"}\n")
}