mirror of
https://github.com/golang/go
synced 2024-11-21 11:54:39 -07:00
log/slog: export Source method in Record for custom handler support
Currently, the `source` method in `slog.Record` is not accessible to
custom handlers, requiring developers to re-implement logic for
retrieving source location information. This commit exports the `source`
method as `Source`, enabling consistent access for custom logging
handlers and reducing code redundancy.
Fixes #70280
Change-Id: I3eb3bc60658abc5de95697a10bddd11ab54c6e13
GitHub-Last-Rev: 5c37e88ee5
GitHub-Pull-Request: golang/go#70281
This commit is contained in:
parent
583d750fa1
commit
9121c71a6e
@ -294,7 +294,7 @@ func (h *commonHandler) handle(r Record) error {
|
||||
}
|
||||
// source
|
||||
if h.opts.AddSource {
|
||||
state.appendAttr(Any(SourceKey, r.source()))
|
||||
state.appendAttr(Any(SourceKey, r.Source()))
|
||||
}
|
||||
key = MessageKey
|
||||
msg := r.Message
|
||||
|
@ -530,7 +530,7 @@ func TestJSONAndTextHandlers(t *testing.T) {
|
||||
},
|
||||
} {
|
||||
r := NewRecord(testTime, LevelInfo, "message", callerPC(2))
|
||||
line := strconv.Itoa(r.source().Line)
|
||||
line := strconv.Itoa(r.Source().Line)
|
||||
r.AddAttrs(test.attrs...)
|
||||
var buf bytes.Buffer
|
||||
opts := HandlerOptions{ReplaceAttr: test.replace, AddSource: test.addSource}
|
||||
|
@ -185,7 +185,7 @@ 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()
|
||||
gotFile := filepath.Base(got.File)
|
||||
if got.Function != wantFunc || gotFile != wantFile || got.Line != wantLine {
|
||||
t.Errorf("got (%s, %s, %d), want (%s, %s, %d)",
|
||||
|
@ -211,11 +211,11 @@ func (s *Source) group() Value {
|
||||
return GroupValue(as...)
|
||||
}
|
||||
|
||||
// source returns a Source for the log event.
|
||||
// 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 {
|
||||
func (r Record) Source() *Source {
|
||||
fs := runtime.CallersFrames([]uintptr{r.PC})
|
||||
f, _ := fs.Next()
|
||||
return &Source{
|
||||
|
@ -56,7 +56,7 @@ func TestRecordSource(t *testing.T) {
|
||||
pc = callerPC(test.depth + 1)
|
||||
}
|
||||
r := NewRecord(time.Time{}, 0, "", pc)
|
||||
got := r.source()
|
||||
got := r.Source()
|
||||
if i := strings.LastIndexByte(got.File, '/'); i >= 0 {
|
||||
got.File = got.File[i+1:]
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user