From 02a94e502d0d48a459d19ae94ee089af7eeba32c Mon Sep 17 00:00:00 2001 From: Josue Giron Date: Sat, 21 Nov 2026 19:49:31 +0000 Subject: [PATCH] fix(logger): pass the caller pc to handler wrappers A wrapper set with WithHandlerWrapper or SetHandlerWrapper saw record.PC point at logger.(*Logger).log. Build the record with the caller's PC, the same call site as the source attribute. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- logger/logger.go | 23 ++++++++++-- logger/utils.go | 8 +++++ wrapper_test.go | 91 ++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 121 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8f14a01..7f5b203 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ logger.Info("service started") ### Handler wrappers -`WithHandlerWrapper` (instance) and `SetHandlerWrapper` (package-level logger) wrap the JSON or text handler the logger builds with any `func(slog.Handler) slog.Handler`, such as the `otel` handler below. The built handler still encodes the record, so the level, the custom level names and `source` keep working. The wrapper is kept when the handler changes later (`SetJSONHandler`, `SetTextHandler`, `NewJSONHandler`, `NewTextHandler`), so the option order does not matter. A nil wrapper removes it. +`WithHandlerWrapper` (instance) and `SetHandlerWrapper` (package-level logger) wrap the JSON or text handler the logger builds with any `func(slog.Handler) slog.Handler`, such as the `otel` handler below. The built handler still encodes the record, so the level, the custom level names and `source` keep working. Since v1.7.5 the record a wrapper receives carries the caller's program counter in `record.PC`, the same call site as `source`, so a wrapper with `AddSource` or a bridge that reads `record.PC` reports the code that logged. The wrapper is kept when the handler changes later (`SetJSONHandler`, `SetTextHandler`, `NewJSONHandler`, `NewTextHandler`), so the option order does not matter. A nil wrapper removes it. ## OpenTelemetry diff --git a/logger/logger.go b/logger/logger.go index 6ba9e18..19c6e60 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -15,6 +15,7 @@ import ( "os" "slices" "sync" + "time" ) // Priority represents the level of importance for log messages. Higher values indicate greater importance. @@ -197,7 +198,14 @@ func (l *Logger) SetHandlerWrapper(wrap func(slog.Handler) slog.Handler) { // log is called directly by every exported logging method, so that a // calldepth of 3 reports the caller of that method: runtime.Callers, callers, // log, the method, then its caller. +// +// The record is built here rather than with slog.Logger.Log, so that its PC is +// that caller too: a handler wrapper that reads record.PC (AddSource, an +// OpenTelemetry bridge) reports the same call site as the source attribute. func (l *Logger) log(ctx context.Context, level slog.Level, msg string, args []any) { + if ctx == nil { + ctx = context.Background() + } cfg := l.snapshot() if cfg.logger == nil || !cfg.logger.Enabled(ctx, level) { return @@ -205,15 +213,26 @@ func (l *Logger) log(ctx context.Context, level slog.Level, msg string, args []a // Clip so appends never write into spare capacity of the caller's slice; // a copy made by expandCodedErrors is ours to extend. args = expandCodedErrors(slices.Clip(args)) + var pc uintptr if cfg.addSource { withStack := level == slog.LevelDebug && cfg.debugStack depth := 1 if withStack { depth = maxStackDepth } - args = append(args, sourceAttr(callers(cfg.calldepth+1, depth), withStack)) + pcs := callers(cfg.calldepth+1, depth) + if len(pcs) > 0 { + pc = pcs[0] + } + args = append(args, sourceAttr(pcs, withStack)) + } else { + pc = callerPC(cfg.calldepth + 1) } - cfg.logger.Log(ctx, level, msg, args...) + record := slog.NewRecord(time.Now(), level, msg, pc) + record.Add(args...) + // A logging call has no error to return and no other place to report a + // failed write; slog.Logger.Log drops the handler's error the same way. + _ = cfg.logger.Handler().Handle(ctx, record) } // SetJSONHandler configures the logger to emit JSON logs to the provided writer. diff --git a/logger/utils.go b/logger/utils.go index e6d38e6..650c8bd 100644 --- a/logger/utils.go +++ b/logger/utils.go @@ -35,6 +35,14 @@ func callers(skip, depth int) []uintptr { return pcs[:runtime.Callers(skip, pcs)] } +// callerPC returns the first program counter callers(skip, 1) would return, +// without allocating, or 0 when the stack is shorter than skip. +func callerPC(skip int) uintptr { + var pcs [1]uintptr + runtime.Callers(skip, pcs[:]) + return pcs[0] +} + // sourceAttr builds the "source" group from pcs, whose first entry is the // call site to report. withStack adds a stack trace that starts at that call // site. diff --git a/wrapper_test.go b/wrapper_test.go index 8ffc002..935fff9 100644 --- a/wrapper_test.go +++ b/wrapper_test.go @@ -5,6 +5,8 @@ import ( "context" "io" "log/slog" + "path/filepath" + "runtime" "strings" "testing" "time" @@ -216,3 +218,92 @@ func TestSetHandlerWrapperOnZeroValueLoggerDoesNotPanic(t *testing.T) { }) } } + +// pcRecordingHandler records the call site that record.PC points at, which is +// what a wrapper with AddSource or an OpenTelemetry bridge reports. +type pcRecordingHandler struct { + slog.Handler + site *callSite +} + +func (h pcRecordingHandler) Handle(ctx context.Context, record slog.Record) error { + frame, _ := runtime.CallersFrames([]uintptr{record.PC}).Next() + *h.site = callSite{ + function: frame.Function[strings.LastIndex(frame.Function, ".")+1:], + file: filepath.Base(frame.File), + line: frame.Line, + } + return h.Handler.Handle(ctx, record) +} + +func newPCRecordingWrapper() (func(slog.Handler) slog.Handler, *callSite) { + site := new(callSite) + return func(next slog.Handler) slog.Handler { + return pcRecordingHandler{Handler: next, site: site} + }, site +} + +func TestHandlerWrapperSeesCallerPC(t *testing.T) { + t.Run("instance API", func(t *testing.T) { + wrap, got := newPCRecordingWrapper() + instance := New(WithJSONHandler(io.Discard), WithHandlerWrapper(wrap)) + + want := nextLine() + instance.Info("hello") + + if *got != want { + t.Fatalf("record.PC = %+v, want %+v", *got, want) + } + }) + + t.Run("instance API without source metadata", func(t *testing.T) { + wrap, got := newPCRecordingWrapper() + instance := New(WithJSONHandler(io.Discard), WithHandlerWrapper(wrap), WithSource(false)) + + want := nextLine() + instance.WarnContext(context.Background(), "hello") + + if *got != want { + t.Fatalf("record.PC = %+v, want %+v", *got, want) + } + }) + + t.Run("package-level helpers", func(t *testing.T) { + usePackageJSONHandler(t) + wrap, got := newPCRecordingWrapper() + SetHandlerWrapper(wrap) + t.Cleanup(func() { SetHandlerWrapper(nil) }) + + want := nextLine() + InfoC(context.Background(), "hello") + + if *got != want { + t.Fatalf("record.PC = %+v, want %+v", *got, want) + } + }) +} + +// contextRecordingHandler records whether Handle received a nil context. +type contextRecordingHandler struct { + slog.Handler + gotNil *bool +} + +func (h contextRecordingHandler) Handle(ctx context.Context, record slog.Record) error { + *h.gotNil = ctx == nil + return h.Handler.Handle(ctx, record) +} + +func TestHandlerWrapperNeverSeesNilContext(t *testing.T) { + gotNil := new(bool) + instance := New(WithJSONHandler(io.Discard), WithHandlerWrapper(func(next slog.Handler) slog.Handler { + return contextRecordingHandler{Handler: next, gotNil: gotNil} + })) + var nilContext context.Context + + instance.InfoContext(nilContext, "hello") + + if *gotNil { + t.Fatal("expected a nil context to reach the handler as context.Background()") + } +}