]> Cypherpunks repositories - gostls13.git/commitdiff
log/slog: make TextHandler discard empty Source
authorAntonio Pitasi <antonio@pitasi.dev>
Wed, 21 May 2025 09:58:13 +0000 (11:58 +0200)
committerSean Liao <sean@liao.dev>
Sat, 24 May 2025 15:48:53 +0000 (08:48 -0700)
Fixes #73808

Change-Id: Ica4b7a63eebbf0fff41d68f4de928f9da90c8ada
Reviewed-on: https://go-review.googlesource.com/c/go/+/674875
Reviewed-by: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>

src/log/slog/handler.go
src/log/slog/handler_test.go
src/log/slog/record.go

index e56be5f494b84e4ea3abad16f4a9ef27f79ef9a1..26eb4b82fc8b5742933808d9677ebd75a58bfd39 100644 (file)
@@ -492,6 +492,9 @@ func (s *handleState) appendAttr(a Attr) bool {
        // Special case: Source.
        if v := a.Value; v.Kind() == KindAny {
                if src, ok := v.Any().(*Source); ok {
+                       if src.isEmpty() {
+                               return false
+                       }
                        if s.h.json {
                                a.Value = src.group()
                        } else {
index 445f43f1f5467ae47d8c8b0530b30e47d206dc19..3c4c36912c2f964effca2896461c99a11f430f8f 100644 (file)
@@ -652,7 +652,7 @@ func TestJSONAndTextHandlersWithUnavailableSource(t *testing.T) {
                h    Handler
                want string
        }{
-               {"text", NewTextHandler(&buf, opts), "source=:0 msg=message"},
+               {"text", NewTextHandler(&buf, opts), "msg=message"},
                {"json", NewJSONHandler(&buf, opts), `{"msg":"message"}`},
        } {
                t.Run(test.name, func(t *testing.T) {
index 53ecc67cc88ecaba87e0065a2688155d6aa80f84..3b4e68ce766f5fe3f1a0df3cef18833836ad92a9 100644 (file)
@@ -211,6 +211,9 @@ func (s *Source) group() Value {
        return GroupValue(as...)
 }
 
+// isEmpty returns whether the Source struct is nil or only contains zero fields.
+func (s *Source) isEmpty() bool { return s == nil || *s == 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.