From e03566db7097fd7252e3f1ca4e1c2ca076718f74 Mon Sep 17 00:00:00 2001 From: Mitar Date: Thu, 12 Oct 2023 22:37:52 +0200 Subject: [PATCH] Add FormatPrepare to ConsoleWriter. --- console.go | 9 +++++++++ console_test.go | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/console.go b/console.go index 28279885..02104f40 100644 --- a/console.go +++ b/console.go @@ -76,6 +76,8 @@ type ConsoleWriter struct { FormatErrFieldValue Formatter FormatExtra func(map[string]interface{}, *bytes.Buffer) error + + FormatPrepare func(map[string]interface{}) error } // NewConsoleWriter creates and initializes a new ConsoleWriter. @@ -124,6 +126,13 @@ func (w ConsoleWriter) Write(p []byte) (n int, err error) { return n, fmt.Errorf("cannot decode event: %s", err) } + if w.FormatPrepare != nil { + err = w.FormatPrepare(evt) + if err != nil { + return n, err + } + } + for _, p := range w.PartsOrder { w.writePart(buf, evt, p) } diff --git a/console_test.go b/console_test.go index 0265672d..bdb70a0e 100644 --- a/console_test.go +++ b/console_test.go @@ -418,6 +418,29 @@ func TestConsoleWriterConfiguration(t *testing.T) { } }) + t.Run("Sets FormatPrepare", func(t *testing.T) { + buf := &bytes.Buffer{} + w := zerolog.ConsoleWriter{ + Out: buf, NoColor: true, PartsOrder: []string{"level", "message"}, + FormatPrepare: func(evt map[string]interface{}) error { + evt["message"] = fmt.Sprintf("msg=%s", evt["message"]) + return nil + }, + } + + evt := `{"level": "info", "message": "Foobar"}` + _, err := w.Write([]byte(evt)) + if err != nil { + t.Errorf("Unexpected error when writing output: %s", err) + } + + expectedOutput := "INF msg=Foobar\n" + actualOutput := buf.String() + if actualOutput != expectedOutput { + 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)