Skip to content

Commit

Permalink
Merge pull request #3 from madkins23/zerotime
Browse files Browse the repository at this point in the history
Don't log the time field if it is zero
  • Loading branch information
phsym authored Jan 12, 2024
2 parents bdde01c + 685e372 commit 5a5b0af
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down

0 comments on commit 5a5b0af

Please sign in to comment.