From 044ca4e5c878c785e2c69e5ebcb3d44bf97abc9f Mon Sep 17 00:00:00 2001 From: Ernesto Alejandro Santana Hidalgo Date: Sun, 4 May 2025 04:30:25 +0000 Subject: 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: bd81afe5a502bf0e2d03c30d0f5199a532cc4c62 GitHub-Pull-Request: golang/go#70281 Reviewed-on: https://go-review.googlesource.com/c/go/+/626976 Reviewed-by: qiu laidongfeng2 <2645477756@qq.com> Reviewed-by: Jonathan Amsterdam Reviewed-by: Cherry Mui LUCI-TryBot-Result: Go LUCI --- src/log/slog/handler_test.go | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) (limited to 'src/log/slog/handler_test.go') diff --git a/src/log/slog/handler_test.go b/src/log/slog/handler_test.go index 9f8d518e96..445f43f1f5 100644 --- a/src/log/slog/handler_test.go +++ b/src/log/slog/handler_test.go @@ -547,7 +547,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} @@ -634,6 +638,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. -- cgit v1.3-5-g9baa