Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't log zero timestamp #7

Merged
merged 1 commit into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading