My my, how time flies! There are still a few seats available, and there’s still time to sign up.
Learn how to get the most out of the tests in your Go app!
One feature I often see overlooked capability of the log/slog package, is to extract log key/value pairs from context:
Contexts
Some handlers may wish to include information from the context.Context that is available at the call site. One example of such information is the identifier for the current span when tracing is enabled.
The Logger.Log and Logger.LogAttrs methods take a context as a first argument, as do their corresponding top-level functions.
Although the convenience methods on Logger (Info and so on) and the corresponding top-level functions do not take a context, the alternatives ending in “Context” do. For example,
slog.InfoContext(ctx, "message")It is recommended to pass a context to an output method if one is available.
Why is this frequently overlooked?
Well, one reason is that the handlers bundled in the standard library do not, by default, extract any key/value pairs from the context!
So while the official recommendation is to pass context, when available, unless you’re using a third-party logging handler, you’re passing the context to a black hole.
Is it still good advice to pass context? Yes, it probably is. When you’re writing new code,the cost of passing context is negligible. But at some possible future date, when you add a custom or third-party log handler that requires context, retrofitting your entire application can be quite painful! (Ask me how I know….)