Skip to content

Commit 5a5b0af

Browse files
authored
Merge pull request #3 from madkins23/zerotime
Don't log the time field if it is zero
2 parents bdde01c + 685e372 commit 5a5b0af

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

encoding.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,10 @@ func (e encoder) writeColoredDuration(w *buffer, d time.Duration, c ANSIMod) {
6969
}
7070

7171
func (e encoder) writeTimestamp(buf *buffer, tt time.Time) {
72-
e.writeColoredTime(buf, tt, e.opts.TimeFormat, e.opts.Theme.Timestamp())
73-
buf.AppendByte(' ')
72+
if !tt.IsZero() {
73+
e.writeColoredTime(buf, tt, e.opts.TimeFormat, e.opts.Theme.Timestamp())
74+
buf.AppendByte(' ')
75+
}
7476
}
7577

7678
func (e encoder) writeSource(buf *buffer, pc uintptr, cwd string) {

handler_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,19 @@ func TestHandler_TimeFormat(t *testing.T) {
2626
AssertEqual(t, expected, buf.String())
2727
}
2828

29+
// Handlers should not log the time field if it is zero.
30+
// '- If r.Time is the zero time, ignore the time.'
31+
// https://pkg.go.dev/log/slog@master#Handler
32+
func TestHandler_TimeZero(t *testing.T) {
33+
buf := bytes.Buffer{}
34+
h := NewHandler(&buf, &HandlerOptions{TimeFormat: time.RFC3339Nano, NoColor: true})
35+
rec := slog.NewRecord(time.Time{}, slog.LevelInfo, "foobar", 0)
36+
AssertNoError(t, h.Handle(context.Background(), rec))
37+
38+
expected := fmt.Sprintf("INF foobar\n")
39+
AssertEqual(t, expected, buf.String())
40+
}
41+
2942
func TestHandler_NoColor(t *testing.T) {
3043
buf := bytes.Buffer{}
3144
h := NewHandler(&buf, &HandlerOptions{NoColor: true})

0 commit comments

Comments
 (0)