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 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
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"
)

// ContextExtractor can be used to extract fields from a context.
type ContextExtractor 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
contextExtractor ContextExtractor
}

// 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
if h.contextExtractor != nil {
contextFields = h.contextExtractor(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 TestContextExtractor(t *testing.T) {
key := testContextKey("testkey")
fac, logs := observer.New(zapcore.DebugLevel)
ctx := context.WithValue(context.Background(), key, "testvalue")

sl := slog.New(NewHandler(fac, WithContextExtractor(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 @@ func AddStacktraceAt(lvl slog.Level) Option {
log.addStackAt = lvl
})
}

// .WithContextExtractor configures the Logger to extract fields from the context,
func WithContextExtractor(extractor ContextExtractor) Option {
return optionFunc(func(log *Handler) {
log.contextExtractor = extractor
})
}