From e57554019b4bd70efa62e0dfff9af5307af4c97a Mon Sep 17 00:00:00 2001 From: junya koyama Date: Sat, 3 Feb 2024 07:58:09 +0900 Subject: [PATCH] zapslog: inline group if empty key #1402 Signed-off-by: junya koyama --- exp/zapslog/handler.go | 4 ++++ exp/zapslog/handler_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/exp/zapslog/handler.go b/exp/zapslog/handler.go index 982d9bccd..5abef1c0d 100644 --- a/exp/zapslog/handler.go +++ b/exp/zapslog/handler.go @@ -88,6 +88,10 @@ func convertAttrToField(attr slog.Attr) zapcore.Field { case slog.KindUint64: return zap.Uint64(attr.Key, attr.Value.Uint64()) case slog.KindGroup: + if attr.Key == "" { + // Inlines recursively. + return zap.Inline(groupObject(attr.Value.Group())) + } return zap.Object(attr.Key, groupObject(attr.Value.Group())) case slog.KindLogValuer: return convertAttrToField(slog.Attr{ diff --git a/exp/zapslog/handler_test.go b/exp/zapslog/handler_test.go index 68339df62..4011e3ae2 100644 --- a/exp/zapslog/handler_test.go +++ b/exp/zapslog/handler_test.go @@ -150,6 +150,39 @@ func TestWithName(t *testing.T) { }) } +func TestInlineGroup(t *testing.T) { + t.Parallel() + fac, observedLogs := observer.New(zapcore.DebugLevel) + t.Run("inline-group", func(t *testing.T) { + sl := slog.New(NewHandler(fac)) + sl.Info("msg", "a", "b", slog.Group("", slog.String("c", "d")), "e", "f") + + logs := observedLogs.TakeAll() + require.Len(t, logs, 1, "Expected exactly one entry to be logged") + entry := logs[0] + assert.Equal(t, "", entry.LoggerName, "Unexpected logger name") + assert.Equal(t, map[string]any{ + "a": "b", + "c": "d", + "e": "f", + }, logs[0].ContextMap(), "Unexpected context") + }) + t.Run("inline-group-recursive", func(t *testing.T) { + sl := slog.New(NewHandler(fac)) + sl.Info("msg", "a", "b", slog.Group("", slog.Group("", slog.Group("", slog.String("c", "d"))), slog.Group("", "e", "f"))) + + logs := observedLogs.TakeAll() + require.Len(t, logs, 1, "Expected exactly one entry to be logged") + entry := logs[0] + assert.Equal(t, "", entry.LoggerName, "Unexpected logger name") + assert.Equal(t, map[string]any{ + "a": "b", + "c": "d", + "e": "f", + }, logs[0].ContextMap(), "Unexpected context") + }) +} + type Token string func (Token) LogValue() slog.Value {