-
Notifications
You must be signed in to change notification settings - Fork 87
Description
The Golang community decided against introducing an API for passing a slog.Logger or slog.Handler via a context.Context. logr supports this with NewContext and FromContext[orDiscard] for logr.Logger. https://github.com/veqryn/slog-context supports this for slog.Logger. Both are not interoperable.
This issue is about exploring whether further work is needed in this area and if so, what that should be.
Here are some possibilities:
-
Add
slogr.NewContext(ctx context.Context, logger *slog.Logger)andslogr.FromContext(ctx context.Context) *slog.Loggeron top of the correspondinglogrfunctions, with conversion to and fromlogr.Logger. Currently there's only documentation for how to write such functions. Drawback: additional allocations, in particular on each retrieval. -
Move the conversion code from
slogrand the context key definition intologr/internal. The value for that key can be either alogr.Loggeror a* slog.Logger. Thenslogr.NewContextcan store its parameter under that context key andslogr.FromContextcan retrieved it without allocations. Bothslogr.FromContextandlogr.FromContextwould have to do type checks and convert if needed. Drawback: the mainlogrpackage depends on slog when built with Go > 1.21 (currently it doesn't).
If we do option 2, then https://github.com/veqryn/slog-context could use slogr under the hood to set and retrieve a logger instance and code using one or the other package would become interoperable.
Note that option 2 suggests to store and retrieve a slog.Logger because that avoids the memory allocation. Storing a slog.Handler implies that code must construct a slog.Logger when it wants to use one. We could also have functions for storing and retrieving a slog.Handler as a third alternative.