From a9a8199d2dd3578d37e459618515f34b5e917f8d Mon Sep 17 00:00:00 2001
From: Patrick Scheid
Date: Fri, 21 Oct 2022 23:32:46 +0200
Subject: [PATCH] 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.
---
console.go | 2 +-
console_test.go | 26 ++++++++++++++++++++++++++
2 files changed, 27 insertions(+), 1 deletion(-)
diff --git a/console.go b/console.go
index 9f6ffbfa..9cc3285e 100644
--- a/console.go
+++ b/console.go
@@ -337,7 +337,7 @@ func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
t := ""
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 {
diff --git a/console_test.go b/console_test.go
index 98a4e27b..18c2db70 100644
--- a/console_test.go
+++ b/console_test.go
@@ -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) {