diff options
Diffstat (limited to '')
-rw-r--r-- | logging/test/handler.go | 55 |
1 files changed, 51 insertions, 4 deletions
diff --git a/logging/test/handler.go b/logging/test/handler.go index d1f5d40..3eef031 100644 --- a/logging/test/handler.go +++ b/logging/test/handler.go @@ -58,21 +58,65 @@ func (h *MockHandler) Enabled(ctx context.Context, level slog.Level) bool { return true // Capture all logs } +func normalizeAttrs(attrs []slog.Attr) []slog.Attr { + var out []slog.Attr + for _, attr := range attrs { + if attr.Equal(slog.Attr{}) { + continue + } + + v := attr.Value.Resolve() + + switch v.Kind() { + case slog.KindGroup: + // Skip empty group + if len(v.Group()) == 0 { + continue + } + + inner := normalizeAttrs(v.Group()) + + // Flatten if group key is empty + if attr.Key == "" { + out = append(out, inner...) + } else { + out = append(out, slog.Attr{ + Key: attr.Key, + Value: slog.GroupValue(inner...), + }) + } + default: + out = append(out, slog.Attr{ + Key: attr.Key, + Value: v, + }) + } + } + return out +} + func (h *MockHandler) Handle(ctx context.Context, r slog.Record) error { + newRecord := slog.NewRecord(r.Time, r.Level, r.Message, r.PC) if h.parent == nil { - r.Clone() - h.recorder.Append(r) + attrs := []slog.Attr{} + r.Attrs(func(attr slog.Attr) bool { + attrs = append(attrs, attr) + return true + }) + attrs = normalizeAttrs(attrs) + newRecord.AddAttrs(attrs...) + h.recorder.Append(newRecord) return nil } - newRecord := slog.NewRecord(r.Time, r.Level, r.Message, r.PC) - attrs := slices.Clone(h.attrs) r.Attrs(func(attr slog.Attr) bool { attrs = append(attrs, attr) return true }) + attrs = normalizeAttrs(attrs) + if h.group != "" { newRecord.AddAttrs(slog.Attr{ Key: h.group, @@ -86,6 +130,9 @@ func (h *MockHandler) Handle(ctx context.Context, r slog.Record) error { } func (h *MockHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + if len(attrs) == 0 { + return h + } return &MockHandler{ recorder: h.recorder, parent: h, |