From f76d643702a30fbffecdfe50831e11881c96ceb3 Mon Sep 17 00:00:00 2001 From: Aaron Lehmann Date: Wed, 28 Sep 2016 11:55:00 +0100 Subject: [PATCH] Fix formatting of wrapped errors when colors are used There are two different code paths for rendering a key/value pair. The non-color version uses a type switch that handles specific types such as "error", and the color version uses the %+v printf format specifier. This causes an inconsistency between the two formats. In particular, errors created using the github.com/pkg/errors package will include a stack trace of where the error was created when printed to the terminal, but not to a file. Printing the stack trace as part of the log field is probably not the right behavior. The output is also inconsistent between the two forms because strings are not quoted/escaped when colors are used. This can make log output unparseable. Fix this by making both code paths use the type switch and escaping rules. Fix the escaping code to pass the error value to Fprintf, not the error itself, which seems to be necessary to avoid blank output with errors created by github.com/pkg/errors. --- text_formatter.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/text_formatter.go b/text_formatter.go index cce61f2..9114b3c 100644 --- a/text_formatter.go +++ b/text_formatter.go @@ -122,7 +122,8 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin } for _, k := range keys { v := entry.Data[k] - fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v) + fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) + f.appendValue(b, v) } } @@ -142,7 +143,11 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf b.WriteString(key) b.WriteByte('=') + f.appendValue(b, value) + b.WriteByte(' ') +} +func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { switch value := value.(type) { case string: if !needsQuoting(value) { @@ -155,11 +160,9 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf if !needsQuoting(errmsg) { b.WriteString(errmsg) } else { - fmt.Fprintf(b, "%q", value) + fmt.Fprintf(b, "%q", errmsg) } default: fmt.Fprint(b, value) } - - b.WriteByte(' ') }