slogcolor is a little, customizable color handler for log/slog
. It enhances log readability by color-coding log levels and supports flexible formatting options.
Its output is inspired by XMRig and zerolog.
package main
import (
"os"
"time"
"errors"
"log/slog"
"github.com/MatusOllah/slogcolor"
)
func main() {
// Configure slog to use slogcolor by default for colored output
slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, slogcolor.DefaultOptions)))
slog.Info("Initializing")
slog.Debug("Init done", "duration", 500*time.Millisecond)
slog.Warn("Slow request!", "method", "GET", "path", "/api/users", "duration", 750*time.Millisecond)
slog.Error("DB connection lost!", "err", errors.New("connection reset"), "db", "horalky")
}
The output format can also be customized using the Options
like this:
opts := &slogcolor.Options{
Level: slog.LevelDebug,
TimeFormat: time.RFC3339,
SrcFileMode: slog.Nop,
}
slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, opts)))
or like this:
opts := slogcolor.DefaultOptions
opts.Level = slog.LevelDebug
opts.TimeFormat = time.RFC3339
opts.SrcFileMode = slog.Nop
slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, opts)))
Messages can be prefixed with Prefix
like this:
slog.Info(slogcolor.Prefix("MyPrefix", "kajšmentke"))
slog.Info(slogcolor.Prefix("SceneController", "switching scene"))
Colors are enabled by default but can be disabled using Options.NoColor
. Particularly useful for automatically enabling colors based on the terminal capabilities using e.g. the go-isatty
package.
w := os.Stderr
opts := slogcolor.DefaultOptions
opts.NoColor = !isatty.IsTerminal(w.Fd())
slog.SetDefault(slog.New(slogcolor.NewHandler(w, opts)))