Skip to content

Commit

Permalink
fix stack position: rebuilt stack in handler4LogSlog.Handle() while u…
Browse files Browse the repository at this point in the history
…sed as a log/slog Handler
  • Loading branch information
hedzr committed Oct 20, 2024
1 parent 08b804b commit 252344d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
11 changes: 11 additions & 0 deletions slog/adapters.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package slog
import (
"context"
logslog "log/slog"
"runtime"
)

// NewSlogHandler makes a log/slog Handler to adapt into standard slog.
Expand Down Expand Up @@ -93,6 +94,16 @@ func (s *handler4LogSlog) Handle(ctx context.Context, rec logslog.Record) error
lvl := convertLogSlogLevel(rec.Level)
if wi, ok := s.Logger.(LogSlogAware); ok {
fields := convertLogSlogRecordAttrs(rec)

// rec.PC would be abandoned because we want skip the extra frames
ei := 0
if sa, ok := s.Logger.(interface{ Skip() int }); ok {
ei = sa.Skip()
}
var pcs [1]uintptr
runtime.Callers(3+1+ei, pcs[:])
rec.PC = pcs[0]

wi.WriteThru(ctx, lvl, rec.Time, rec.PC, rec.Message, fields)
} else {
fields := convertLogSlogRecordAttrs(rec)
Expand Down
2 changes: 1 addition & 1 deletion slog/pc.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ type PrintCtx struct {
kvps Attrs
clr, bg color.Color
now time.Time
stackFrame uintptr
stackFrame uintptr // the caller's stack frames

prefix string
inGroupedMode bool
Expand Down

0 comments on commit 252344d

Please sign in to comment.