Allow to exclude parts from console output (#272)

Co-authored-by: CrazyMax <crazy-max@users.noreply.github.com>
This commit is contained in:
CrazyMax 2020-11-29 10:13:56 +01:00 committed by GitHub
parent cac3894be4
commit 29d8dac5e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View File

@ -57,6 +57,9 @@ type ConsoleWriter struct {
// PartsOrder defines the order of parts in output. // PartsOrder defines the order of parts in output.
PartsOrder []string PartsOrder []string
// PartsExclude defines parts to not display in output.
PartsExclude []string
FormatTimestamp Formatter FormatTimestamp Formatter
FormatLevel Formatter FormatLevel Formatter
FormatCaller Formatter FormatCaller Formatter
@ -208,6 +211,14 @@ func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer
func (w ConsoleWriter) writePart(buf *bytes.Buffer, evt map[string]interface{}, p string) { func (w ConsoleWriter) writePart(buf *bytes.Buffer, evt map[string]interface{}, p string) {
var f Formatter var f Formatter
if w.PartsExclude != nil && len(w.PartsExclude) > 0 {
for _, exclude := range w.PartsExclude {
if exclude == p {
return
}
}
}
switch p { switch p {
case LevelFieldName: case LevelFieldName:
if w.FormatLevel == nil { if w.FormatLevel == nil {

View File

@ -336,6 +336,24 @@ 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 PartsExclude", func(t *testing.T) {
buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true, PartsExclude: []string{"time"}}
d := time.Unix(0, 0).UTC().Format(time.RFC3339)
evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}`
_, err := w.Write([]byte(evt))
if err != nil {
t.Errorf("Unexpected error when writing output: %s", err)
}
expectedOutput := "INF Foobar\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) {