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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
23 changes: 21 additions & 2 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"os"
"slices"
"sync"
"time"
)

// Priority represents the level of importance for log messages. Higher values indicate greater importance.
Expand Down Expand Up @@ -197,23 +198,41 @@ 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
}
// 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.
Expand Down
8 changes: 8 additions & 0 deletions logger/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
91 changes: 91 additions & 0 deletions wrapper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"context"
"io"
"log/slog"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -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()")
}
}
Loading