From 11db26d5a66bf9c78b0fe11f40b1d50e8da63f9d Mon Sep 17 00:00:00 2001 From: TJ Hoplock Date: Tue, 14 Jan 2025 18:15:28 -0500 Subject: [PATCH] fix: don't nest empty group keys, better follow slog.Hanlder interface Test snippets to show change: Before: ``` level=info caller=slogtest.go:97 time=2025-01-14T17:36:28.125642737-05:00 msg=msg a=b .G.c=d e=f ``` After: ``` level=info caller=slogtest.go:97 time=2025-01-14T18:09:01.253906842-05:00 msg=msg a=b G.c=d e=f ``` Signed-off-by: TJ Hoplock --- handler.go | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/handler.go b/handler.go index e998c2a..d2b84a6 100644 --- a/handler.go +++ b/handler.go @@ -130,11 +130,25 @@ func appendPair(pairs []any, groupPrefix string, attr slog.Attr) []any { switch attr.Value.Kind() { case slog.KindGroup: - if attr.Key != "" { - groupPrefix = groupPrefix + "." + attr.Key - } - for _, a := range attr.Value.Group() { - pairs = appendPair(pairs, groupPrefix, a) + attrs := attr.Value.Group() + if len(attrs) > 0 { + // Only process groups that have non-empty attributes + // to properly conform to slog.Handler interface + // contract. + + if attr.Key != "" { + // If a group's key is empty, attributes should + // be inlined to properly conform to + // slog.Handler interface contract. + if groupPrefix != "" { + groupPrefix = groupPrefix + "." + attr.Key + } else { + groupPrefix = attr.Key + } + } + for _, a := range attrs { + pairs = appendPair(pairs, groupPrefix, a) + } } default: key := attr.Key