Skip to content

Commit

Permalink
Show group name.
Browse files Browse the repository at this point in the history
  • Loading branch information
jmalloc committed Jul 18, 2024
1 parent 8d8ee21 commit 8a1e311
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ The format is based on [Keep a Changelog], and this project adheres to

## [Unreleased]

### Changed

- The group name is now displayed in the "meta-data" section at the beginning of
the log line.

### Fixed

- `With()` now places attributes in the current group instead of at the root.
Expand Down
10 changes: 10 additions & 0 deletions spruce.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ func (h *handler) Handle(_ context.Context, rec slog.Record) error {
buf.WriteByte('+')
}
buf.WriteString(elapsed.String())

for i, g := range h.groups {
if i == 0 {
buf.WriteByte(' ')
} else {
buf.WriteByte('.')
}
buf.WriteString(g)
}

buf.WriteString("] ")

buf.WriteString(rec.Message)
Expand Down
24 changes: 20 additions & 4 deletions spruce_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func TestHandler_WithAttrs_inGroupKey(t *testing.T) {

l.Info("<message>")
s.Expect(
`[INFO <timestamp>] <message>`,
`[INFO <timestamp> <group>] <message>`,
`╰─┬ <group>`,
` ╰── <key> β”ˆ <value>`,
)
Expand All @@ -155,12 +155,28 @@ func TestHandler_WithGroup(t *testing.T) {

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

func TestHandler_WithGroup_nested(t *testing.T) {
s := &testingTStub{T: t}
l := spruce.
NewTestLogger(s).
WithGroup("<parent>").
WithGroup("<child>")

l.Info("<message>", "<key>", "<value>")
s.Expect(
`[INFO <timestamp> <parent>.<child>] <message>`,
`╰─┬ <parent>`,
` ╰─┬ <child>`,
` ╰── <key> β”ˆ <value>`,
)
}

type testingTStub struct {
T *testing.T
actual []string
Expand All @@ -172,11 +188,11 @@ func (s *testingTStub) Log(args ...any) {
}

func (s *testingTStub) Expect(lines ...string) {
timestamp := regexp.MustCompile(`\[([A-Z]+) .+?\]`)
timestamp := regexp.MustCompile(`\[([A-Z]+) [^\]\s]+`)

expect := strings.Join(lines, "\n")
for _, line := range s.actual {
line = timestamp.ReplaceAllString(line, "[$1 <timestamp>]")
line = timestamp.ReplaceAllString(line, "[$1 <timestamp>")
if line == expect {
return
}
Expand Down

0 comments on commit 8a1e311

Please sign in to comment.