Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion slogger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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"`
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
70 changes: 70 additions & 0 deletions slogger/level.go
Original file line number Diff line number Diff line change
@@ -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)}
}
145 changes: 145 additions & 0 deletions slogger/level_test.go
Original file line number Diff line number Diff line change
@@ -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
}
4 changes: 3 additions & 1 deletion slogger/slogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
46 changes: 46 additions & 0 deletions slogger/slogger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
Loading