diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d3e2c3..82e8052 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,13 @@ 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 +## [0.2.2] - 2024-07-19 + +### Changed + +- Display a wall-clock time (instead of the duration since the logger was + created) when logging to an `io.Writer`.' + ## [0.2.1] - 2024-07-19 ### Changed diff --git a/spruce.go b/spruce.go index afe3792..91b6fff 100644 --- a/spruce.go +++ b/spruce.go @@ -6,14 +6,13 @@ import ( "log/slog" "slices" "strings" - "time" ) type handler struct { - log func(string) error - attrs []slog.Attr - groups []string - epoch time.Time + log func(string) error + attrs []slog.Attr + groups []string + writeTime func(*strings.Builder, slog.Record) } func (h *handler) Enabled(context.Context, slog.Level) bool { @@ -53,15 +52,10 @@ func (h *handler) Handle(_ context.Context, rec slog.Record) error { level := rec.Level.String() - elapsed := rec.Time.Sub(h.epoch) - buf.WriteByte('[') buf.WriteString(level) buf.WriteByte(' ') - if elapsed > 0 { - buf.WriteByte('+') - } - buf.WriteString(elapsed.String()) + h.writeTime(buf, rec) for i, g := range h.groups { if i == 0 { @@ -142,18 +136,18 @@ func writeAttrs( func (h *handler) WithAttrs(attrs []slog.Attr) slog.Handler { return &handler{ - log: h.log, - attrs: append(slices.Clone(h.attrs), attrs...), - groups: h.groups, - epoch: h.epoch, + log: h.log, + attrs: append(slices.Clone(h.attrs), attrs...), + groups: h.groups, + writeTime: h.writeTime, } } func (h *handler) WithGroup(name string) slog.Handler { return &handler{ - log: h.log, - attrs: h.attrs, - groups: append(slices.Clone(h.groups), name), - epoch: h.epoch, + log: h.log, + attrs: h.attrs, + groups: append(slices.Clone(h.groups), name), + writeTime: h.writeTime, } } diff --git a/stream.go b/stream.go index 080330e..abd423b 100644 --- a/stream.go +++ b/stream.go @@ -3,6 +3,7 @@ package spruce import ( "io" "log/slog" + "strings" "time" ) @@ -25,6 +26,10 @@ func NewStreamHandler(w io.Writer) slog.Handler { } return nil }, - epoch: time.Now(), + writeTime: func(w *strings.Builder, rec slog.Record) { + w.WriteString( + rec.Time.Format(time.RFC3339), + ) + }, } } diff --git a/testing.go b/testing.go index 29dc249..423fbd0 100644 --- a/testing.go +++ b/testing.go @@ -2,6 +2,7 @@ package spruce import ( "log/slog" + "strings" "testing" "time" ) @@ -20,11 +21,19 @@ func NewTestLogger(t TestingT) *slog.Logger { // NewTestHandler returns a new [slog.Handler] that writes to t. func NewTestHandler(t TestingT) slog.Handler { + epoch := time.Now() + return &handler{ log: func(s string) error { t.Log(s) return nil }, - epoch: time.Now(), + writeTime: func(w *strings.Builder, rec slog.Record) { + elapsed := rec.Time.Sub(epoch) + if elapsed > 0 { + w.WriteByte('+') + } + w.WriteString(elapsed.String()) + }, } }