β οΈ This post links to an external website. β οΈ
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 customsloghandler. To start with, let's talk about what I mean by handlers and custom handlers.A
sloghandler controls what slog does with calls to logging methods. More concretely, a handler determines the format of log output.slogitself provides two handlers: one outputs JSON and the other outputskey=valuepairs. You choose a handler when you create asloglogger.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=3In addition to the two default handlers,
slogmakes 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
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.