-
Notifications
You must be signed in to change notification settings - Fork 5
Formatters
Michael Kenney edited this page Aug 18, 2018
·
3 revisions
The built-in logging formatters are:
-
log.TextFormatter. Logs the event in colors if stdout is a tty, otherwise without colors.-
Note: to force colored output when there is no TTY, set the
ForceTTYfield totrue. To force no colored output even if there is a TTY set theDisableTTYfield totrue. For Windows, see github.com/mattn/go-colorable. - All options are listed in the generated docs.
-
Note: to force colored output when there is no TTY, set the
-
log.JSONFormatter. Logs fields as JSON.- All options are listed in the generated docs.
You can define your formatter by implementing the Formatter interface, requiring a Format method. Format takes an *Entry. entry.Data is a Fields type (map[string]interface{}) with all your fields as well as the default ones:
type MyJSONFormatter struct {
}
log.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
// Note: this doesn't include Level, Message, and Time, which are also
// available on Entry.
serialized, err := json.Marshal(entry.Data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}Which one will reach the other side of the river: The one who dreams of a raft, or the one that hitchhikes to the next bridge?