Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support extra arbitrary data at the end of console log #416

Merged
merged 1 commit into from Jul 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 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)

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

err = buf.WriteByte('\n')
if err != nil {
return n, err
}
mitar marked this conversation as resolved.
Show resolved Hide resolved

_, 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")
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