From 8a1e3116ca019b515332a2c755efa77c3173afb8 Mon Sep 17 00:00:00 2001 From: James Harris Date: Fri, 19 Jul 2024 09:20:02 +1000 Subject: [PATCH] Show group name. --- CHANGELOG.md | 5 +++++ spruce.go | 10 ++++++++++ spruce_test.go | 24 ++++++++++++++++++++---- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5a257f..583f67a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/spruce.go b/spruce.go index f30d1f3..afe3792 100644 --- a/spruce.go +++ b/spruce.go @@ -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) diff --git a/spruce_test.go b/spruce_test.go index 6f1716f..70bfdb0 100644 --- a/spruce_test.go +++ b/spruce_test.go @@ -141,7 +141,7 @@ func TestHandler_WithAttrs_inGroupKey(t *testing.T) { l.Info("") s.Expect( - `[INFO ] `, + `[INFO ] `, `╰─┬ `, ` ╰── `, ) @@ -155,12 +155,28 @@ func TestHandler_WithGroup(t *testing.T) { l.Info("", "", "") s.Expect( - `[INFO ] `, + `[INFO ] `, `╰─┬ `, ` ╰── `, ) } +func TestHandler_WithGroup_nested(t *testing.T) { + s := &testingTStub{T: t} + l := spruce. + NewTestLogger(s). + WithGroup(""). + WithGroup("") + + l.Info("", "", "") + s.Expect( + `[INFO .] `, + `╰─┬ `, + ` ╰─┬ `, + ` ╰── `, + ) +} + type testingTStub struct { T *testing.T actual []string @@ -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 ]") + line = timestamp.ReplaceAllString(line, "[$1 ") if line == expect { return }