Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make it possible to extract fields from the context in the slog adapter #1372

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
23 changes: 17 additions & 6 deletions exp/zapslog/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ import (
"go.uber.org/zap/zapcore"
)

// ContextFieldExtractor can be used to extract a field from a context.
type ContextFieldExtractor func(ctx context.Context) []zapcore.Field

// Handler implements the slog.Handler by writing to a zap Core.
type Handler struct {
core zapcore.Core
name string // logger name
addCaller bool
addStackAt slog.Level
callerSkip int
core zapcore.Core
name string // logger name
addCaller bool
addStackAt slog.Level
callerSkip int
contextFieldExtractors []ContextFieldExtractor
}

// NewHandler builds a [Handler] that writes to the supplied [zapcore.Core]
Expand Down Expand Up @@ -157,7 +161,14 @@ func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
ce.Stack = stacktrace.Take(3 + h.callerSkip)
}

fields := make([]zapcore.Field, 0, record.NumAttrs())
var contextFields []zapcore.Field
for _, extractor := range h.contextFieldExtractors {
contextFields = append(contextFields, extractor(ctx)...)
}

fields := make([]zapcore.Field, 0, record.NumAttrs()+len(contextFields))
fields = append(fields, contextFields...)

record.Attrs(func(attr slog.Attr) bool {
fields = append(fields, convertAttrToField(attr))
return true
Expand Down
20 changes: 20 additions & 0 deletions exp/zapslog/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,20 @@
package zapslog

import (
"context"
"log/slog"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
)

type testContextKey string

func TestAddCaller(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -189,3 +193,19 @@ func TestAttrKinds(t *testing.T) {
},
entry.ContextMap())
}

func TestContextFieldExtractor(t *testing.T) {
key := testContextKey("testkey")
fac, logs := observer.New(zapcore.DebugLevel)
ctx := context.WithValue(context.Background(), key, "testvalue")

sl := slog.New(NewHandler(fac, WithContextFieldExtractors(func(ctx context.Context) []zapcore.Field {
v := ctx.Value(key).(string)
return []zapcore.Field{zap.String("testkey", v)}
})))
sl.InfoContext(ctx, "msg")
lines := logs.TakeAll()

require.Len(t, lines, 1)
require.Equal(t, "testvalue", lines[0].ContextMap()["testkey"])
}
7 changes: 7 additions & 0 deletions exp/zapslog/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,10 @@
log.addStackAt = lvl
})
}

// .WithContextFieldExtractors configures the Logger to extract fields from the context.

Check failure on line 74 in exp/zapslog/options.go

View workflow job for this annotation

GitHub Actions / Lint

exported: comment on exported function WithContextFieldExtractors should be of the form "WithContextFieldExtractors ..." (revive)
func WithContextFieldExtractors(extractors ...ContextFieldExtractor) Option {
return optionFunc(func(log *Handler) {
log.contextFieldExtractors = append(log.contextFieldExtractors, extractors...)
})
}
Loading