• Stars
    star
    698
  • Rank 64,841 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created over 1 year ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌈 slog.Handler that writes tinted (colorized) logs

tint: 🌈 slog.Handler that writes tinted logs

Go Reference Go Report Card



Package tint provides a slog.Handler that writes tinted (colorized) logs. The output format is inspired by the zerolog.ConsoleWriter.

The output format can be customized using Options which is a drop-in replacement for slog.HandlerOptions.

go get github.com/lmittmann/tint

Note

slog is an experimental structured logging package, that will be added to the standard library in Go 1.21. See #56345 for tracking the progress.

Usage

// create a new logger
logger := slog.New(tint.NewHandler(os.Stderr, nil))

// set global logger with custom options
slog.SetDefault(slog.New(
    tint.NewHandler(os.Stderr, &tint.Options{
        Level:      slog.LevelDebug,
        TimeFormat: time.Kitchen,
    }),
))

Customize

ReplaceAttr can be used to alter or drop attributes. If set, it is called on each non-group attribute before it is logged. See slog.HandlerOptions for details.

// create a new logger that doesn't write the time
logger := slog.New(tint.NewHandler(os.Stderr, &tint.Options{
    ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
        if a.Key == slog.TimeKey && len(groups) == 0 {
            return slog.Attr{}
        }
        return a
    },
}))

Automatically Enable/Disable Colors

Colors are enabled by default and can be disabled using the Options.NoColor attribute. To automatically enable colors based on the terminal capabilities, use e.g. the go-isatty package.

w := os.Stderr
logger := slog.New(
    tint.NewHandler(w, &tint.Options{
        NoColor: !isatty.IsTerminal(w.Fd()),
    }),
)

Windows Support

Color support on Windows can be added by using e.g. the go-colorable package.

w := os.Stderr
logger := slog.New(
    tint.NewHandler(colorable.NewColorable(w), nil),
)