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

This commit is contained in:
Mitar 2022-07-18 15:00:50 -07:00 committed by GitHub
parent 4c85986254
commit 4099072c03
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 0 deletions

View File

@ -74,6 +74,8 @@ type ConsoleWriter struct {
FormatFieldValue Formatter FormatFieldValue Formatter
FormatErrFieldName Formatter FormatErrFieldName Formatter
FormatErrFieldValue Formatter FormatErrFieldValue Formatter
FormatExtra func(map[string]interface{}, *bytes.Buffer) error
} }
// NewConsoleWriter creates and initializes a new ConsoleWriter. // NewConsoleWriter creates and initializes a new ConsoleWriter.
@ -128,10 +130,18 @@ func (w ConsoleWriter) Write(p []byte) (n int, err error) {
w.writeFields(evt, buf) w.writeFields(evt, buf)
if w.FormatExtra != nil {
err = w.FormatExtra(evt, buf)
if err != nil {
return n, err
}
}
err = buf.WriteByte('\n') err = buf.WriteByte('\n')
if err != nil { if err != nil {
return n, err return n, err
} }
_, err = buf.WriteTo(w.Out) _, err = buf.WriteTo(w.Out)
return len(p), err return len(p), err
} }

View File

@ -375,6 +375,29 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) 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) { func BenchmarkConsoleWriter(b *testing.B) {