Skip to content

Commit

Permalink
zapslog: inline group if empty key uber-go#1402
Browse files Browse the repository at this point in the history
Signed-off-by: junya koyama <arukiidou@yahoo.co.jp>
  • Loading branch information
arukiidou committed Feb 2, 2024
1 parent 27b96e3 commit e575540
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
4 changes: 4 additions & 0 deletions exp/zapslog/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down
33 changes: 33 additions & 0 deletions exp/zapslog/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit e575540

Please sign in to comment.