We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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 usingslog
, but I'm going to discuss testing a customslog
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 outputskey=value
pairs. You choose a handler when you create aslog
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 withtesting/slogtest
.
continue reading on telemachus.me
β οΈ This post links to an external website. β οΈ
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.