Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

zapslog: Handle empty attrs centrally #1351

Merged
merged 1 commit into from Sep 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 5 additions & 7 deletions exp/zapslog/handler.go
Expand Up @@ -67,6 +67,11 @@ func (gs groupObject) MarshalLogObject(enc zapcore.ObjectEncoder) error {
}

func convertAttrToField(attr slog.Attr) zapcore.Field {
if attr.Equal(slog.Attr{}) {
// Ignore empty attrs.
return zap.Skip()
}

switch attr.Value.Kind() {
case slog.KindBool:
return zap.Bool(attr.Key, attr.Value.Bool())
Expand Down Expand Up @@ -154,10 +159,6 @@ func (h *Handler) Handle(ctx context.Context, record slog.Record) error {

fields := make([]zapcore.Field, 0, record.NumAttrs())
record.Attrs(func(attr slog.Attr) bool {
if attr.Equal(slog.Attr{}) {
return true // ignore empty attributes
}

fields = append(fields, convertAttrToField(attr))
return true
})
Expand All @@ -170,9 +171,6 @@ func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
fields := make([]zapcore.Field, 0, len(attrs))
for _, attr := range attrs {
if attr.Equal(slog.Attr{}) {
continue // ignore empty attributes
}
fields = append(fields, convertAttrToField(attr))
}
return h.withFields(fields...)
Expand Down
12 changes: 12 additions & 0 deletions exp/zapslog/handler_test.go
Expand Up @@ -113,6 +113,18 @@ func TestEmptyAttr(t *testing.T) {
"foo": "bar",
}, logs[0].ContextMap(), "Unexpected context")
})

t.Run("Group", func(t *testing.T) {
sl.With("k", slog.GroupValue(slog.String("foo", "bar"), slog.Attr{})).Info("msg")

logs := observedLogs.TakeAll()
require.Len(t, logs, 1, "Expected exactly one entry to be logged")
assert.Equal(t, map[string]any{
"k": map[string]any{
"foo": "bar",
},
}, logs[0].ContextMap(), "Unexpected context")
})
}

func TestWithName(t *testing.T) {
Expand Down