The Go team recently released Go 1.21, and one of its major features was the addition of slog, a structured logging module, to the standard library. There are a lot of good discussions about using slog, but I'm going to discuss testing a custom slog handler. To start with, let's talk about what I mean by handlers and custom handlers.

A slog handler controls what slog does with calls to logging methods. More concretely, a handler determines the format of log output. slog itself provides two handlers: one outputs JSON and the other outputs key=value pairs. You choose a handler when you create a slog logger.

jLogger := slog.New(slog.NewJSONHandler(os.Stderr, nil))
tLogger := slog.New(slog.NewTextHandler(os.Stdout, nil))
// Later…
jLogger.Info("hello", "count", 3)
// {"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3}
tLogger.Info("hello", "count", 3)
// time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3

In addition to the two default handlers, slog makes it relatively easy to create a handler. Jonathan Amsterdam, slog's author, has even written a guide to writing slog handlers. If you're interested in writing a handler, I highly recommend that you read the whole guide. But I'm only going to discuss the pros and cons of testing a handler with testing/slogtest.

continue reading on telemachus.me

⚠️ This post links to an external website. ⚠️