From 685e372713e4ef069d7c031de98a67c5deae1d48 Mon Sep 17 00:00:00 2001 From: mAdkins Date: Fri, 12 Jan 2024 05:54:41 -0800 Subject: [PATCH] Don't log the time field if it is zero --- encoding.go | 6 ++++-- handler_test.go | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/encoding.go b/encoding.go index 31028fa..6088e65 100644 --- a/encoding.go +++ b/encoding.go @@ -69,8 +69,10 @@ func (e encoder) writeColoredDuration(w *buffer, d time.Duration, c ANSIMod) { } func (e encoder) writeTimestamp(buf *buffer, tt time.Time) { - e.writeColoredTime(buf, tt, e.opts.TimeFormat, e.opts.Theme.Timestamp()) - buf.AppendByte(' ') + if !tt.IsZero() { + e.writeColoredTime(buf, tt, e.opts.TimeFormat, e.opts.Theme.Timestamp()) + buf.AppendByte(' ') + } } func (e encoder) writeSource(buf *buffer, pc uintptr, cwd string) { diff --git a/handler_test.go b/handler_test.go index 1d92d3c..84bbbff 100644 --- a/handler_test.go +++ b/handler_test.go @@ -26,6 +26,19 @@ func TestHandler_TimeFormat(t *testing.T) { AssertEqual(t, expected, buf.String()) } +// Handlers should not log the time field if it is zero. +// '- If r.Time is the zero time, ignore the time.' +// https://pkg.go.dev/log/slog@master#Handler +func TestHandler_TimeZero(t *testing.T) { + buf := bytes.Buffer{} + h := NewHandler(&buf, &HandlerOptions{TimeFormat: time.RFC3339Nano, NoColor: true}) + rec := slog.NewRecord(time.Time{}, slog.LevelInfo, "foobar", 0) + AssertNoError(t, h.Handle(context.Background(), rec)) + + expected := fmt.Sprintf("INF foobar\n") + AssertEqual(t, expected, buf.String()) +} + func TestHandler_NoColor(t *testing.T) { buf := bytes.Buffer{} h := NewHandler(&buf, &HandlerOptions{NoColor: true})