Skip to content

Commit

Permalink
zapslog: Handle empty attrs centrally (#1351)
Browse files Browse the repository at this point in the history
Follow-up to #1344 to handle empty attributes using a skip field in a
single place, so each caller of `convertAttrToField` doesn't have to
check for empty attributes explicitly.
  • Loading branch information
prashantv authored Sep 9, 2023
1 parent 2b35963 commit b7aed24
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
12 changes: 5 additions & 7 deletions exp/zapslog/handler.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit b7aed24

Please sign in to comment.