Skip to content

Commit

Permalink
console: handle timestamp in ms correctly + fix UTC
Browse files Browse the repository at this point in the history
  • Loading branch information
rs committed Apr 25, 2019
1 parent 33f552e commit acf3980
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
7 changes: 6 additions & 1 deletion console.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,12 @@ func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
if err != nil {
t = tt.String()
} else {
ts := time.Unix(i, 0)
var sec, nsec int64 = i, 0
if TimeFieldFormat == TimeFormatUnixMs {
nsec = int64(time.Duration(i) * time.Millisecond)
sec = 0
}
ts := time.Unix(sec, nsec).UTC()
t = ts.Format(timeFormat)
}
}
Expand Down
28 changes: 25 additions & 3 deletions console_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,36 @@ func TestConsoleWriter(t *testing.T) {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true}
w := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.StampMilli, NoColor: true}

_, err := w.Write([]byte(`{"time": 1234, "level": "debug", "message": "Foobar", "foo": "bar"}`))
if err != nil {
t.Errorf("Unexpected error when writing output: %s", err)
}

expectedOutput := "Jan 1 00:20:34.000 DBG Foobar foo=bar\n"
actualOutput := buf.String()
if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
}
})

t.Run("Unix timestamp ms input format", func(t *testing.T) {
of := zerolog.TimeFieldFormat
defer func() {
zerolog.TimeFieldFormat = of
}()
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs

buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.StampMilli, NoColor: true}

_, err := w.Write([]byte(`{"time": 0, "level": "debug", "message": "Foobar", "foo": "bar"}`))
_, err := w.Write([]byte(`{"time": 1234567, "level": "debug", "message": "Foobar", "foo": "bar"}`))
if err != nil {
t.Errorf("Unexpected error when writing output: %s", err)
}

expectedOutput := "4:00PM DBG Foobar foo=bar\n"
expectedOutput := "Jan 1 00:20:34.567 DBG Foobar foo=bar\n"
actualOutput := buf.String()
if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
Expand Down

0 comments on commit acf3980

Please sign in to comment.