mirror of
https://github.com/golang/go
synced 2024-11-21 23:44: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
This commit is contained in:
parent
583d750fa1
commit
5c37e88ee5
@ -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)",
|
||||
|
@ -215,7 +215,7 @@ func (s *Source) group() Value {
|
||||
// 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