Skip to content

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 ForceTTY field to true. To force no colored output even if there is a TTY set the DisableTTY field to true. For Windows, see github.com/mattn/go-colorable.
    • All options are listed in the generated docs.
  • log.JSONFormatter. Logs fields as JSON.

Custom log formatting:

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
}

Clone this wiki locally