Skip to content

Commit

Permalink
Fix With() when logger has a group.
Browse files Browse the repository at this point in the history
  • Loading branch information
jmalloc committed Jul 18, 2024
1 parent 5fb6911 commit 8d8ee21
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ The format is based on [Keep a Changelog], and this project adheres to
[Keep a Changelog]: https://keepachangelog.com/en/1.0.0/
[Semantic Versioning]: https://semver.org/spec/v2.0.0.html

## [Unreleased]

### Fixed

- `With()` now places attributes in the current group instead of at the root.

## [0.2.0] - 2024-07-19

### Added
Expand Down
8 changes: 7 additions & 1 deletion spruce.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,21 @@ func (h *handler) Enabled(context.Context, slog.Level) bool {

func (h *handler) Handle(_ context.Context, rec slog.Record) error {
buf := &strings.Builder{}
attrs := slices.Clone(h.attrs)
var attrs []slog.Attr

if len(h.groups) == 0 {
attrs = slices.Clone(h.attrs)
rec.Attrs(func(attr slog.Attr) bool {
attrs = append(attrs, attr)
return true
})
} else {
var grouped []any

for _, attr := range h.attrs {
grouped = append(grouped, attr)
}

rec.Attrs(func(attr slog.Attr) bool {
grouped = append(grouped, attr)
return true
Expand Down
15 changes: 15 additions & 0 deletions spruce_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,21 @@ func TestHandler_WithAttrs_sameKey(t *testing.T) {
)
}

func TestHandler_WithAttrs_inGroupKey(t *testing.T) {
s := &testingTStub{T: t}
l := spruce.
NewTestLogger(s).
WithGroup("<group>").
With("<key>", "<value>")

l.Info("<message>")
s.Expect(
`[INFO <timestamp>] <message>`,
`╰─┬ <group>`,
` ╰── <key> ┈ <value>`,
)
}

func TestHandler_WithGroup(t *testing.T) {
s := &testingTStub{T: t}
l := spruce.
Expand Down

0 comments on commit 8d8ee21

Please sign in to comment.