Skip to content

Commit

Permalink
Merge pull request #7 from madkins23/zero-time
Browse files Browse the repository at this point in the history
Don't log zero timestamp
  • Loading branch information
phsym authored Sep 23, 2024
2 parents 0098b07 + 28a6c14 commit 11b85af
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
4 changes: 3 additions & 1 deletion zerolog.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@ func (h *Handler) endLog(rec *slog.Record, evt *zerolog.Event) {
evt.Str(zerolog.CallerFieldName, fmt.Sprintf("%s:%d", frame.File, frame.Line))
}

evt.Time(zerolog.TimestampFieldName, rec.Time)
if !rec.Time.IsZero() {
evt.Time(zerolog.TimestampFieldName, rec.Time)
}
evt.Msg(rec.Message)
}

Expand Down
32 changes: 32 additions & 0 deletions zerolog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,38 @@ func TestZerolog_Group(t *testing.T) {
}
}

// TestZerolog_ZeroTime verifies that a zero timestamp will not be logged.
// - "- If r.Time is the zero time, ignore the time."
// - https://pkg.go.dev/log/slog@master#Handler
func TestZerolog_ZeroTime(t *testing.T) {
out := bytes.Buffer{}
hdl := NewJsonHandler(&out, &HandlerOptions{AddSource: true})
_ = hdl.Handle(context.Background(),
slog.NewRecord(time.Time{}, slog.LevelInfo, "foobar", 0))
m := map[string]any{}
if err := json.NewDecoder(&out).Decode(&m); err != nil {
t.Fatalf("Failed to json decode log output: %s", err.Error())
}
if _, found := m[slog.TimeKey]; found {
t.Fatalf("Empty '%s' key %v", slog.TimeKey, m[slog.TimeKey])
}
}

// TestZerolog_NonZeroTime verifies that a non-zero timestamp will be logged.
func TestZerolog_NonZeroTime(t *testing.T) {
out := bytes.Buffer{}
hdl := NewJsonHandler(&out, &HandlerOptions{AddSource: true})
_ = hdl.Handle(context.Background(),
slog.NewRecord(time.Now(), slog.LevelInfo, "foobar", 0))
m := map[string]any{}
if err := json.NewDecoder(&out).Decode(&m); err != nil {
t.Fatalf("Failed to json decode log output: %s", err.Error())
}
if now, found := m[slog.TimeKey]; !found && now != nil {
t.Fatalf("No '%s' key %v", slog.TimeKey, m[slog.TimeKey])
}
}

func TestZerolog_AddSource(t *testing.T) {
out := bytes.Buffer{}
hdl := NewJsonHandler(&out, &HandlerOptions{AddSource: true})
Expand Down

0 comments on commit 11b85af

Please sign in to comment.