Skip to content

contextual logging for slog #234

@pohly

Description

@pohly

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:

  1. Add slogr.NewContext(ctx context.Context, logger *slog.Logger) and slogr.FromContext(ctx context.Context) *slog.Logger on top of the corresponding logr functions, with conversion to and from logr.Logger. Currently there's only documentation for how to write such functions. Drawback: additional allocations, in particular on each retrieval.

  2. Move the conversion code from slogr and the context key definition into logr/internal. The value for that key can be either a logr.Logger or a * slog.Logger. Then slogr.NewContext can store its parameter under that context key and slogr.FromContext can retrieved it without allocations. Both slogr.FromContext and logr.FromContext would have to do type checks and convert if needed. Drawback: the main logr 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.

cc @veqryn @antichris

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions