Controlling Log output coloring

By default, logs output on console should be colorized depending on the detected TTY.

Customize level title, text, color and styling at general.

Import golog and pio:

  1. import (
  2. "github.com/kataras/golog"
  3. "github.com/kataras/pio"
  4. // [...]
  5. )

Get a level to customize e.g. DebugLevel:

  1. level := golog.Levels[golog.DebugLevel]

You have full control over his text, title and style:

  1. // The Name of the Level
  2. // that named (lowercased) will be used
  3. // to convert a string level on `SetLevel`
  4. // to the correct Level type.
  5. Name string
  6. // AlternativeNames are the names that can be referred to this specific log level.
  7. // i.e Name = "warn"
  8. // AlternativeNames = []string{"warning"}, it's an optional field,
  9. // therefore we keep Name as a simple string and created this new field.
  10. AlternativeNames []string
  11. // Tha Title is the prefix of the log level.
  12. // See `ColorCode` and `Style` too.
  13. // Both `ColorCode` and `Style` should be respected across writers.
  14. Title string
  15. // ColorCode a color for the `Title`.
  16. ColorCode int
  17. // Style one or more rich options for the `Title`.
  18. Style []pio.RichOption

Example Code:

  1. level := golog.Levels[golog.DebugLevel]
  2. level.Name = "debug" // default
  3. level.Title = "[DBUG]" // default
  4. level.ColorCode = pio.Yellow // default

To change the output format:

  1. app.Logger().SetFormat("json", " ")

To register a custom Formatter:

  1. app.Logger().RegisterFormatter(new(myFormatter))

The golog.Formatter interface looks like this:

  1. // Formatter is responsible to print a log to the logger's writer.
  2. type Formatter interface {
  3. // The name of the formatter.
  4. String() string
  5. // Set any options and return a clone,
  6. // generic. See `Logger.SetFormat`.
  7. Options(opts ...interface{}) Formatter
  8. // Writes the "log" to "dest" logger.
  9. Format(dest io.Writer, log *Log) bool
  10. }

To change the output and the format per level:

  1. app.Logger().SetLevelOutput("error", os.Stderr)
  2. app.Logger().SetLevelFormat("json")