From 114cfd5effe74505529dcabbe0cb0e9c1de1fc82 Mon Sep 17 00:00:00 2001 From: Alexander Menshchikov Date: Wed, 11 Nov 2026 12:09:05 +0300 Subject: [PATCH] Add the context-aware log level WithLevel puts a log level into the context, and the handler of the logger reads it back: the level of the context takes precedence over the level of the logger, so a single request can be logged at its own level. The check is made in the Enabled method of the handler, before the record is formatted. The level of the context is only seen by the *Context methods of the logger, the ones that take a context. The logger built by New and NewToContext wraps its handler, so the level of the context is applied out of the box. NewLevelHandler is exported for the loggers that are built by the user. --- slogger/README.md | 48 ++++++++++++- slogger/level.go | 70 +++++++++++++++++++ slogger/level_test.go | 145 ++++++++++++++++++++++++++++++++++++++++ slogger/slogger.go | 4 +- slogger/slogger_test.go | 46 +++++++++++++ 5 files changed, 311 insertions(+), 2 deletions(-) create mode 100644 slogger/level.go create mode 100644 slogger/level_test.go diff --git a/slogger/README.md b/slogger/README.md index 73dd5b5..ee9735d 100644 --- a/slogger/README.md +++ b/slogger/README.md @@ -2,7 +2,8 @@ A `log/slog` logger with a configurable format, a hot-reloadable log level, a custom writer, an optional source code position and an optional rewriting of the -attributes. +attributes. The log level can also be set per request through the +[context](https://pkg.go.dev/context). The module is split into two packages: @@ -43,6 +44,10 @@ type Options struct { func New(ctx context.Context, opts Options) (*slog.Logger, error) func NewToContext(ctx context.Context, opts Options) (context.Context, error) + +func WithLevel(ctx context.Context, level slog.Level) context.Context + +func NewLevelHandler(next slog.Handler) slog.Handler ``` - `Leveler` — the current log level: `"DEBUG"`, `"INFO"`, `"WARN"` or `"ERROR"` @@ -60,6 +65,9 @@ func NewToContext(ctx context.Context, opts Options) (context.Context, error) context, so it can be used with the [`ctxlog`](#context-logger) helpers. The returned context is nil if the logger cannot be initialized. +`WithLevel` and `NewLevelHandler` set the log level of a single request; see +[Context log level](#context-log-level). + ## Usage ```go @@ -212,6 +220,44 @@ current level is kept: time=... level=ERROR msg="Failed to parse log level while hot-reload update" error="slog: level string \"bogus\": unknown name" ``` +## Context log level + +The log level is normally the same for the whole application, but a single +request may need a different one — to write the debug records of one request +into the log, or to keep the noisy ones out of it. + +`WithLevel` puts a level into the context, and the handler of the logger reads +it back: + +```go +ctx = slogger.WithLevel(ctx, slog.LevelDebug) + +logger.DebugContext(ctx, "Server started") +``` + +The level of the context takes precedence over the level of the logger: the +records below it are dropped, and the ones above it are written, whatever the +level of the logger is. Without a level in the context the logger behaves as +usual. + +The level is read by the `Enabled` method of the handler, so it is applied +before the record is formatted. The level of the context is only seen by the +`*Context` methods of the logger — the ones that take a context — and by the +[`ctxlog`](#context-logger) helpers, which use them. + +The logger built by `New` and `NewToContext` already wraps its handler, so the +level of the context is applied out of the box. To use it with a handler of +your own, wrap the handler yourself: + +```go +handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}) +logger := slog.New(slogger.NewLevelHandler(handler)) +``` + +`NewLevelHandler` passes the calls other than `Enabled` to the wrapped handler, +so the format, the source code position and the attribute rewriting of the +wrapped handler are kept. + ## Errors `New` returns an error if the level returned by `Leveler` cannot be parsed diff --git a/slogger/level.go b/slogger/level.go new file mode 100644 index 0000000..e2a6246 --- /dev/null +++ b/slogger/level.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: BSD-3-Clause + +package slogger + +import ( + "context" + "log/slog" +) + +type levelKey struct{} + +// WithLevel returns a copy of ctx carrying the given log level. +// +// The level of the context takes precedence over the level of the logger: the +// records below it are dropped, and the ones above it are written, whatever +// the level of the logger is. +func WithLevel(ctx context.Context, level slog.Level) context.Context { + return context.WithValue(ctx, levelKey{}, level) +} + +// levelFromContext returns the log level carried by ctx and whether it is set. +func levelFromContext(ctx context.Context) (slog.Level, bool) { + level, ok := ctx.Value(levelKey{}).(slog.Level) + + return level, ok +} + +var _ slog.Handler = (*levelHandler)(nil) + +// levelHandler is a [slog.Handler] that takes the log level from the context. +// +// If the context carries a log level, it takes precedence over the level of +// the wrapped handler. Otherwise the check is passed to the wrapped handler. +type levelHandler struct { + next slog.Handler +} + +// NewLevelHandler returns a handler that takes the log level from the context +// and passes the other calls to the given handler. +// +// It is the way to apply the level of the context to a logger that is not +// built by [New] or [NewToContext]. +func NewLevelHandler(next slog.Handler) slog.Handler { + return &levelHandler{next: next} +} + +// Enabled reports whether the handler handles the records of the given level. +// +// The level of the context takes precedence: if the context carries a log +// level, the record is handled when its level is not lower than the level of +// the context. Otherwise the check is passed to the wrapped handler. +func (h *levelHandler) Enabled(ctx context.Context, level slog.Level) bool { + if ctxLevel, ok := levelFromContext(ctx); ok { + return level >= ctxLevel + } + + return h.next.Enabled(ctx, level) +} + +func (h *levelHandler) Handle(ctx context.Context, record slog.Record) error { //nolint:gocritic + return h.next.Handle(ctx, record) +} + +func (h *levelHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return &levelHandler{next: h.next.WithAttrs(attrs)} +} + +func (h *levelHandler) WithGroup(name string) slog.Handler { + return &levelHandler{next: h.next.WithGroup(name)} +} diff --git a/slogger/level_test.go b/slogger/level_test.go new file mode 100644 index 0000000..19e4b18 --- /dev/null +++ b/slogger/level_test.go @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: BSD-3-Clause + +package slogger_test + +import ( + "context" + "log/slog" + "testing" + "time" + + . "github.com/nbgrp/pkg/slogger" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLevelHandler_Enabled(t *testing.T) { + t.Parallel() + + t.Run("passes the check to the nested handler", func(t *testing.T) { + t.Parallel() + + handler := NewLevelHandler(&stubHandler{enabled: false}) + + assert.False(t, handler.Enabled(t.Context(), slog.LevelInfo)) + }) + + t.Run("passes the enabled check to the nested handler", func(t *testing.T) { + t.Parallel() + + handler := NewLevelHandler(&stubHandler{enabled: true}) + + assert.True(t, handler.Enabled(t.Context(), slog.LevelInfo)) + }) + + t.Run("uses the level of the context", func(t *testing.T) { + t.Parallel() + + handler := NewLevelHandler(&stubHandler{enabled: false}) + ctx := WithLevel(t.Context(), slog.LevelWarn) + + assert.False(t, handler.Enabled(ctx, slog.LevelInfo)) + assert.True(t, handler.Enabled(ctx, slog.LevelWarn)) + assert.True(t, handler.Enabled(ctx, slog.LevelError)) + }) + + t.Run("the level of the context takes precedence over the nested handler", func(t *testing.T) { + t.Parallel() + + handler := NewLevelHandler(&stubHandler{enabled: false}) + ctx := WithLevel(t.Context(), slog.LevelDebug) + + assert.True(t, handler.Enabled(ctx, slog.LevelDebug)) + }) +} + +func TestLevelHandler_Handle(t *testing.T) { + t.Parallel() + + stub := &stubHandler{enabled: true} + handler := NewLevelHandler(stub) + + require.NoError(t, handler.Handle(t.Context(), slog.NewRecord(time.Time{}, slog.LevelInfo, "Message", 0))) + + require.Len(t, stub.records, 1) + assert.Equal(t, "Message", stub.records[0].Message) +} + +func TestLevelHandler_WithAttrs(t *testing.T) { + t.Parallel() + + stub := &stubHandler{enabled: true} + handler := NewLevelHandler(stub).WithAttrs([]slog.Attr{slog.String("key", "value")}) + + require.Len(t, stub.attrs, 1) + assert.Equal(t, "key", stub.attrs[0].Key) + + // The level of the context is still taken into account. + ctx := WithLevel(t.Context(), slog.LevelError) + assert.False(t, handler.Enabled(ctx, slog.LevelInfo)) +} + +func TestLevelHandler_WithGroup(t *testing.T) { + t.Parallel() + + stub := &stubHandler{enabled: true} + handler := NewLevelHandler(stub).WithGroup("group") + + require.Len(t, stub.groups, 1) + assert.Equal(t, "group", stub.groups[0]) + + // The level of the context is still taken into account. + ctx := WithLevel(t.Context(), slog.LevelError) + assert.False(t, handler.Enabled(ctx, slog.LevelInfo)) +} + +func TestWithLevel(t *testing.T) { + t.Parallel() + + t.Run("the innermost level wins", func(t *testing.T) { + t.Parallel() + + handler := NewLevelHandler(&stubHandler{enabled: false}) + + outer := WithLevel(t.Context(), slog.LevelError) + assert.False(t, handler.Enabled(outer, slog.LevelInfo)) + + inner := WithLevel(outer, slog.LevelDebug) + assert.True(t, handler.Enabled(inner, slog.LevelInfo)) + }) +} + +// stubHandler is a handler that records the calls it receives and reports the +// records of the enabled level as handled. +type stubHandler struct { + enabled bool + records []slog.Record + attrs []slog.Attr + groups []string +} + +// Enabled implements [slog.Handler]. +func (h *stubHandler) Enabled(context.Context, slog.Level) bool { + return h.enabled +} + +// Handle implements [slog.Handler]. +func (h *stubHandler) Handle(_ context.Context, record slog.Record) error { //nolint:gocritic // The signature is fixed by slog.Handler. + h.records = append(h.records, record) + + return nil +} + +// WithAttrs implements [slog.Handler]. +func (h *stubHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + h.attrs = append(h.attrs, attrs...) + + return h +} + +// WithGroup implements [slog.Handler]. +func (h *stubHandler) WithGroup(name string) slog.Handler { + h.groups = append(h.groups, name) + + return h +} diff --git a/slogger/slogger.go b/slogger/slogger.go index baccda6..32c1021 100644 --- a/slogger/slogger.go +++ b/slogger/slogger.go @@ -63,7 +63,9 @@ func New(ctx context.Context, opts Options) (*slog.Logger, error) { return nil, fmt.Errorf("unknown log format %q", opts.Format) } - l := slog.New(handler) + // The level of the context, if any, takes precedence over the level of + // the handler. + l := slog.New(NewLevelHandler(handler)) if opts.LevelReloadCond != nil { go watchLogLevel(ctx, l, opts.LevelReloadCond, level, opts) } diff --git a/slogger/slogger_test.go b/slogger/slogger_test.go index 04470d2..c19d295 100644 --- a/slogger/slogger_test.go +++ b/slogger/slogger_test.go @@ -340,6 +340,52 @@ func TestNew_LevelReload(t *testing.T) { }) } +func TestNew_ContextLevel(t *testing.T) { + t.Parallel() + + t.Run("applies the level of the context", func(t *testing.T) { + t.Parallel() + + buf := &safeBuffer{} + logger, err := New(t.Context(), Options{ + Leveler: func() string { return "ERROR" }, + Format: "text", + Writer: buf, + }) + require.NoError(t, err) + + ctx := WithLevel(t.Context(), slog.LevelDebug) + + logger.DebugContext(ctx, "Accepted message") + logger.ErrorContext(ctx, "Accepted error message") + + out := buf.String() + assert.Contains(t, out, "Accepted message") + assert.Contains(t, out, "Accepted error message") + }) + + t.Run("drops the records below the level of the context", func(t *testing.T) { + t.Parallel() + + buf := &safeBuffer{} + logger, err := New(t.Context(), Options{ + Leveler: func() string { return "DEBUG" }, + Format: "text", + Writer: buf, + }) + require.NoError(t, err) + + ctx := WithLevel(t.Context(), slog.LevelWarn) + + logger.InfoContext(ctx, "Dropped message") + logger.WarnContext(ctx, "Accepted message") + + out := buf.String() + assert.NotContains(t, out, "Dropped message") + assert.Contains(t, out, "Accepted message") + }) +} + func TestNewToContext(t *testing.T) { t.Parallel()