Skip to content

Commit

Permalink
fix ConsoleWriter for TimeFormatMicro (rs#206)
Browse files Browse the repository at this point in the history
  • Loading branch information
wphan authored and rs committed Dec 20, 2019
1 parent f1dd50b commit d2a97b3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
6 changes: 5 additions & 1 deletion console.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,9 +300,13 @@ func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
t = tt.String()
} else {
var sec, nsec int64 = i, 0
if TimeFieldFormat == TimeFormatUnixMs {
switch TimeFieldFormat {
case TimeFormatUnixMs:
nsec = int64(time.Duration(i) * time.Millisecond)
sec = 0
case TimeFormatUnixMicro:
nsec = int64(time.Duration(i) * time.Microsecond)
sec = 0
}
ts := time.Unix(sec, nsec).UTC()
t = ts.Format(timeFormat)
Expand Down
22 changes: 22 additions & 0 deletions console_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,28 @@ func TestConsoleWriter(t *testing.T) {
}
})

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

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

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

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

t.Run("No message field", func(t *testing.T) {
buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true}
Expand Down

0 comments on commit d2a97b3

Please sign in to comment.