sHandler - SLOG Handler with more knobs Link to heading

Go Report Card Go Reference

I really like the ease of Go’s log/slog package, but the default handlers left much to be desired…by me anyway. So I wrote my own

Installation Link to heading

go get disorder.dev/shandler

Features Link to heading

WithJSON Link to heading

Enables JSON output for the log message. This is useful for structured logging.

WithLogLevel Link to heading

Controls the log level for the message. This is useful for filtering messages.

WithTimeFormat Link to heading

Controls the time format for the messages.

WithTextOutputFormat Link to heading

This is a format string that gets used in text based logs. It takes 3 strings: time, level, and message (in that order). Include a newline at the end of your string.

WithStdOut Link to heading

Controls which io.Writer is used for non-error log messages.

WithStdErr Link to heading

Controls which io.Writer is used for error messages.

WithColor Link to heading

Adds color to the log levels in text mode

With{Trace|Debug|Info|Warn|Error|Fatal}Color Link to heading

Overrides the default color for the log level.

WithShortLevels Link to heading

Prints 3 character log levels instead of the full name. In text mode, this helps keep the log lines visually straight.

Examples Link to heading

logger = slog.New(shandler.NewHandler(
	shandler.WithLogLevel(slog.LevelDebug),
	shandler.WithTimeFormat(time.RFC822),
	shandler.WithTextOutputFormat("%s | %s | %s\n"),
	shandler.WithStdErr(os.Stdout),
))
logger.With(slog.String("app", "myapp")).Debug("test")

Trace/Fatal Log Level Link to heading

Library includes an easier way to log trace and fatal messages. This is useful for debugging chatty logs.

ctx := context.TODO()
logger = slog.New(shandler.NewHandler(
	shandler.WithLogLevel(shandler.LevelTrace),
))
logger.Log(ctx, shandler.LevelTrace, "trace test")
logger.Log(ctx, shandler.LevelFatal, "fatal test") // this would appear in StdErr