Skip to content

Commit

Permalink
ConsoleWriter fallbacks to local timezone for missing TZ indicator (#497
Browse files Browse the repository at this point in the history
)

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.
  • Loading branch information
pscheid92 authored Oct 21, 2022
1 parent 89617ff commit a9a8199
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion console.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
t := "<nil>"
switch tt := i.(type) {
case string:
ts, err := time.Parse(TimeFieldFormat, tt)
ts, err := time.ParseInLocation(TimeFieldFormat, tt, time.Local)
if err != nil {
t = tt
} else {
Expand Down
26 changes: 26 additions & 0 deletions console_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,32 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
}
})

t.Run("Uses local time for console writer without time zone", func(t *testing.T) {
// Regression test for issue #483 (check there for more details)

timeFormat := "2006-01-02 15:04:05"
expectedOutput := "2022-10-20 20:24:50 INF Foobar\n"
evt := `{"time": "2022-10-20 20:24:50", "level": "info", "message": "Foobar"}`

of := zerolog.TimeFieldFormat
defer func() {
zerolog.TimeFieldFormat = of
}()
zerolog.TimeFieldFormat = timeFormat

buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true, TimeFormat: timeFormat}
_, err := w.Write([]byte(evt))
if err != nil {
t.Errorf("Unexpected error when writing output: %s", err)
}

actualOutput := buf.String()
if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
}
})
}

func BenchmarkConsoleWriter(b *testing.B) {
Expand Down

0 comments on commit a9a8199

Please sign in to comment.