Skip to content

Commit b7aed24

Browse files
authored
zapslog: Handle empty attrs centrally (#1351)
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.
1 parent 2b35963 commit b7aed24

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

exp/zapslog/handler.go

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ func (gs groupObject) MarshalLogObject(enc zapcore.ObjectEncoder) error {
6767
}
6868

6969
func convertAttrToField(attr slog.Attr) zapcore.Field {
70+
if attr.Equal(slog.Attr{}) {
71+
// Ignore empty attrs.
72+
return zap.Skip()
73+
}
74+
7075
switch attr.Value.Kind() {
7176
case slog.KindBool:
7277
return zap.Bool(attr.Key, attr.Value.Bool())
@@ -154,10 +159,6 @@ func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
154159

155160
fields := make([]zapcore.Field, 0, record.NumAttrs())
156161
record.Attrs(func(attr slog.Attr) bool {
157-
if attr.Equal(slog.Attr{}) {
158-
return true // ignore empty attributes
159-
}
160-
161162
fields = append(fields, convertAttrToField(attr))
162163
return true
163164
})
@@ -170,9 +171,6 @@ func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
170171
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
171172
fields := make([]zapcore.Field, 0, len(attrs))
172173
for _, attr := range attrs {
173-
if attr.Equal(slog.Attr{}) {
174-
continue // ignore empty attributes
175-
}
176174
fields = append(fields, convertAttrToField(attr))
177175
}
178176
return h.withFields(fields...)

exp/zapslog/handler_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,18 @@ func TestEmptyAttr(t *testing.T) {
113113
"foo": "bar",
114114
}, logs[0].ContextMap(), "Unexpected context")
115115
})
116+
117+
t.Run("Group", func(t *testing.T) {
118+
sl.With("k", slog.GroupValue(slog.String("foo", "bar"), slog.Attr{})).Info("msg")
119+
120+
logs := observedLogs.TakeAll()
121+
require.Len(t, logs, 1, "Expected exactly one entry to be logged")
122+
assert.Equal(t, map[string]any{
123+
"k": map[string]any{
124+
"foo": "bar",
125+
},
126+
}, logs[0].ContextMap(), "Unexpected context")
127+
})
116128
}
117129

118130
func TestWithName(t *testing.T) {

0 commit comments

Comments
 (0)