-
Notifications
You must be signed in to change notification settings - Fork 18.5k
Description
It would be helpful if we can attach a slog.Logger to a context.Context, so that added attributes can be shared down the call chain. Much like library zerolog does with functions Ctx and Logger.WithContext).
Now that slog is becoming the standard log interface, it makes sense to also define context attachment. This would allow package authors to look for a logger in a context and if available use when needed. Likewise, it would give the author of a main package all the power to configure the logger, or not.
Use cases
- Request logger created in middleware with request ID and other metadata, passed down in the
http.Requestcontext. - The ability to send the logger into a library, like facilitated in
pgx-zerolog.
Using the current implementation
slog does provide the ability to pass a context using the XXXContext() methods. With a custom handler one could extract data from the context. However, this creates the need of implementing a custom Handler and trying each context value one wants to log. IMO this will result in much boilerplate code.