fix ConsoleWriter for TimeFormatMicro (#206)

This commit is contained in:
wphan 2019-12-20 09:34:21 -08:00 committed by Olivier Poitrey
parent f1dd50b8c6
commit d2a97b366b
2 changed files with 27 additions and 1 deletions

View File

@ -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)

View File

@ -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}