Skip to content

log/slog: export Source method in Record for custom handler support #70281

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

Open
wants to merge 2 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
1 change: 1 addition & 0 deletions api/next/70280.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pkg log/slog, method (r Record) Source() *Source #70280
1 change: 1 addition & 0 deletions doc/next/6-stdlib/99-minor/log/slog/70280.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[Record] now has a Source() method, returning its source location or nil if unavailable.
6 changes: 5 additions & 1 deletion src/log/slog/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,11 @@ func (h *commonHandler) handle(r Record) error {
}
// source
if h.opts.AddSource {
state.appendAttr(Any(SourceKey, r.source()))
src := r.Source()
if src == nil {
src = &Source{}
}
state.appendAttr(Any(SourceKey, src))
}
key = MessageKey
msg := r.Message
Expand Down
40 changes: 39 additions & 1 deletion src/log/slog/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,11 @@ func TestJSONAndTextHandlers(t *testing.T) {
},
} {
r := NewRecord(testTime, LevelInfo, "message", callerPC(2))
line := strconv.Itoa(r.source().Line)
source := r.Source()
if source == nil {
t.Fatal("source is nil")
}
line := strconv.Itoa(source.Line)
r.AddAttrs(test.attrs...)
var buf bytes.Buffer
opts := HandlerOptions{ReplaceAttr: test.replace, AddSource: test.addSource}
Expand Down Expand Up @@ -617,6 +621,40 @@ func TestHandlerEnabled(t *testing.T) {
}
}

func TestJSONAndTextHandlersWithUnavailableSource(t *testing.T) {
// Verify that a nil source does not cause a panic.
// and that the source is empty.
var buf bytes.Buffer
opts := &HandlerOptions{
ReplaceAttr: removeKeys(LevelKey),
AddSource: true,
}

for _, test := range []struct {
name string
h Handler
want string
}{
{"text", NewTextHandler(&buf, opts), "source=:0 msg=message"},
{"json", NewJSONHandler(&buf, opts), `{"msg":"message"}`},
} {
t.Run(test.name, func(t *testing.T) {
buf.Reset()
r := NewRecord(time.Time{}, LevelInfo, "message", 0)
err := test.h.Handle(t.Context(), r)
if err != nil {
t.Fatal(err)
}

want := strings.TrimSpace(test.want)
got := strings.TrimSpace(buf.String())
if got != want {
t.Errorf("\ngot %s\nwant %s", got, want)
}
})
}
}

func TestSecondWith(t *testing.T) {
// Verify that a second call to Logger.With does not corrupt
// the original.
Expand Down
5 changes: 4 additions & 1 deletion src/log/slog/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,10 @@ func TestCallDepth(t *testing.T) {
const wantFunc = "log/slog.TestCallDepth"
const wantFile = "logger_test.go"
wantLine := startLine + count*2
got := h.r.source()
got := h.r.Source()
if got == nil {
t.Fatal("got nil source")
}
gotFile := filepath.Base(got.File)
if got.Function != wantFunc || gotFile != wantFile || got.Line != wantLine {
t.Errorf("got (%s, %s, %d), want (%s, %s, %d)",
Expand Down
13 changes: 8 additions & 5 deletions src/log/slog/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,11 +211,14 @@ func (s *Source) group() Value {
return GroupValue(as...)
}

// source returns a Source for the log event.
// If the Record was created without the necessary information,
// or if the location is unavailable, it returns a non-nil *Source
// with zero fields.
func (r Record) source() *Source {
// Source returns a new Source for the log event using r's PC.
// If the PC field is zero, meaning the Record was created without the necessary information
// or the location is unavailable, then nil is returned.
func (r Record) Source() *Source {
if r.PC == 0 {
return nil
}

fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
return &Source{
Expand Down
23 changes: 17 additions & 6 deletions src/log/slog/record_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,35 @@ func TestRecordAttrs(t *testing.T) {
}

func TestRecordSource(t *testing.T) {
// Zero call depth => empty *Source.
// Zero call depth => nil *Source.
for _, test := range []struct {
depth int
wantFunction string
wantFile string
wantLinePositive bool
wantNil bool
}{
{0, "", "", false},
{-16, "", "", false},
{1, "log/slog.TestRecordSource", "record_test.go", true}, // 1: caller of NewRecord
{2, "testing.tRunner", "testing.go", true},
{0, "", "", false, true},
{-16, "", "", false, true},
{1, "log/slog.TestRecordSource", "record_test.go", true, false}, // 1: caller of NewRecord
{2, "testing.tRunner", "testing.go", true, false},
} {
var pc uintptr
if test.depth > 0 {
pc = callerPC(test.depth + 1)
}
r := NewRecord(time.Time{}, 0, "", pc)
got := r.source()
got := r.Source()
if test.wantNil {
if got != nil {
t.Errorf("depth %d: got non-nil Source, want nil", test.depth)
}
continue
}
if got == nil {
t.Errorf("depth %d: got nil Source, want non-nil", test.depth)
continue
}
if i := strings.LastIndexByte(got.File, '/'); i >= 0 {
got.File = got.File[i+1:]
}
Expand Down