Skip to content

Commit a9a8199

Browse files
authored
ConsoleWriter fallbacks to local timezone for missing TZ indicator (#497)
Closes issue #483 Before: We use time.Parse which defaults to TZ UTC if there is no time zone indicator specified in the time layout string. During the reparsing in ConsoleWriter we therefore added the TZ difference to UTC twice. After: We use time.ParseInLocal where we need to provide a dedicated fallback TZ as a fallback. Since we now fallback to the local TZ, we don't add the TZ difference to UTC twice.
1 parent 89617ff commit a9a8199

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

console.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
337337
t := "<nil>"
338338
switch tt := i.(type) {
339339
case string:
340-
ts, err := time.Parse(TimeFieldFormat, tt)
340+
ts, err := time.ParseInLocation(TimeFieldFormat, tt, time.Local)
341341
if err != nil {
342342
t = tt
343343
} else {

console_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,32 @@ func TestConsoleWriterConfiguration(t *testing.T) {
398398
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
399399
}
400400
})
401+
402+
t.Run("Uses local time for console writer without time zone", func(t *testing.T) {
403+
// Regression test for issue #483 (check there for more details)
404+
405+
timeFormat := "2006-01-02 15:04:05"
406+
expectedOutput := "2022-10-20 20:24:50 INF Foobar\n"
407+
evt := `{"time": "2022-10-20 20:24:50", "level": "info", "message": "Foobar"}`
408+
409+
of := zerolog.TimeFieldFormat
410+
defer func() {
411+
zerolog.TimeFieldFormat = of
412+
}()
413+
zerolog.TimeFieldFormat = timeFormat
414+
415+
buf := &bytes.Buffer{}
416+
w := zerolog.ConsoleWriter{Out: buf, NoColor: true, TimeFormat: timeFormat}
417+
_, err := w.Write([]byte(evt))
418+
if err != nil {
419+
t.Errorf("Unexpected error when writing output: %s", err)
420+
}
421+
422+
actualOutput := buf.String()
423+
if actualOutput != expectedOutput {
424+
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
425+
}
426+
})
401427
}
402428

403429
func BenchmarkConsoleWriter(b *testing.B) {

0 commit comments

Comments
 (0)