diff --git a/text_formatter.go b/text_formatter.go index fc0a408..ee34b50 100644 --- a/text_formatter.go +++ b/text_formatter.go @@ -3,6 +3,7 @@ package logrus import ( "bytes" "fmt" + "regexp" "sort" "strings" "time" @@ -19,11 +20,13 @@ const ( var ( baseTimestamp time.Time isTerminal bool + noQuoteNeeded *regexp.Regexp ) func init() { baseTimestamp = time.Now() isTerminal = IsTerminal() + noQuoteNeeded, _ = regexp.Compile("^[a-zA-Z0-9.-]*$") } func miniTS() int { @@ -87,8 +90,18 @@ func printColored(b *bytes.Buffer, entry *Entry, keys []string) { func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key, value interface{}) { switch value.(type) { - case string, error: - fmt.Fprintf(b, "%v=%q ", key, value) + case string: + if noQuoteNeeded.MatchString(value.(string)) { + fmt.Fprintf(b, "%v=%s ", key, value) + } else { + fmt.Fprintf(b, "%v=%q ", key, value) + } + case error: + if noQuoteNeeded.MatchString(value.(error).Error()) { + fmt.Fprintf(b, "%v=%s ", key, value) + } else { + fmt.Fprintf(b, "%v=%q ", key, value) + } default: fmt.Fprintf(b, "%v=%v ", key, value) } diff --git a/text_formatter_test.go b/text_formatter_test.go new file mode 100644 index 0000000..4e956c9 --- /dev/null +++ b/text_formatter_test.go @@ -0,0 +1,33 @@ +package logrus + +import ( + "bytes" + "errors" + + "testing" +) + +func TestQuoting(t *testing.T) { + tf := new(TextFormatter) + + checkQuoting := func(q bool, value interface{}) { + b, _ := tf.Format(WithField("test", value)) + idx := bytes.LastIndex(b, []byte{'='}) + cont := bytes.Contains(b[idx:], []byte{'"'}) + if cont != q { + if q { + t.Errorf("quoting expected for: %#v", value) + } else { + t.Errorf("quoting not expected for: %#v", value) + } + } + } + + checkQuoting(false, "abcd") + checkQuoting(false, "v1.0") + checkQuoting(true, "/foobar") + checkQuoting(true, "x y") + checkQuoting(true, "x,y") + checkQuoting(false, errors.New("invalid")) + checkQuoting(true, errors.New("invalid argument")) +}