-
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.Logger
on top of the correspondinglogr
functions, 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
slogr
and the context key definition intologr/internal
. The value for that key can be either alogr.Logger
or a* slog.Logger
. Thenslogr.NewContext
can store its parameter under that context key andslogr.FromContext
can retrieved it without allocations. Bothslogr.FromContext
andlogr.FromContext
would have to do type checks and convert if needed. Drawback: the mainlogr
package 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.