Skip to content

Commit

Permalink
Support extra arbitrary data at the end of console log
Browse files Browse the repository at this point in the history
  • Loading branch information
mitar committed Jul 18, 2022
1 parent 43be301 commit 0a1737b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
16 changes: 13 additions & 3 deletions console.go
Expand Up @@ -74,6 +74,8 @@ type ConsoleWriter struct {
FormatFieldValue Formatter
FormatErrFieldName Formatter
FormatErrFieldValue Formatter

FormatExtra func(map[string]interface{}, *bytes.Buffer) error
}

// NewConsoleWriter creates and initializes a new ConsoleWriter.
Expand Down Expand Up @@ -128,10 +130,18 @@ func (w ConsoleWriter) Write(p []byte) (n int, err error) {

w.writeFields(evt, buf)

err = buf.WriteByte('\n')
if err != nil {
return n, err
if w.FormatExtra != nil {
err = w.FormatExtra(evt, buf)
if err != nil {
return n, err
}
} else {
err = buf.WriteByte('\n')
if err != nil {
return n, err
}
}

_, err = buf.WriteTo(w.Out)
return len(p), err
}
Expand Down
23 changes: 23 additions & 0 deletions console_test.go
Expand Up @@ -375,6 +375,29 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
}
})

t.Run("Sets FormatExtra", func(t *testing.T) {
buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{
Out: buf, NoColor: true, PartsOrder: []string{"level", "message"},
FormatExtra: func(evt map[string]interface{}, buf *bytes.Buffer) error {
buf.WriteString("\nAdditional stacktrace\n")
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 Foobar\nAdditional stacktrace\n"
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 0a1737b

Please sign in to comment.