Skip to content

Commit

Permalink
Add FormatPrepare to ConsoleWriter.
Browse files Browse the repository at this point in the history
  • Loading branch information
mitar committed Oct 12, 2023
1 parent ed609e7 commit e03566d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
9 changes: 9 additions & 0 deletions console.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
}
Expand Down
23 changes: 23 additions & 0 deletions console_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit e03566d

Please sign in to comment.