From cfca98e6d9c0082625feae2fe6bde8cb955c370d Mon Sep 17 00:00:00 2001 From: Ben Brooks Date: Tue, 14 Feb 2017 10:53:03 +0000 Subject: [PATCH] Add 'QuoteEmptyFields' option to TextFormatter --- text_formatter.go | 12 +++++++++--- text_formatter_test.go | 6 +++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/text_formatter.go b/text_formatter.go index b4dffa1..51397cc 100644 --- a/text_formatter.go +++ b/text_formatter.go @@ -49,6 +49,9 @@ type TextFormatter struct { // be desired. DisableSorting bool + // QuoteEmptyFields will wrap empty fields in quotes if true + QuoteEmptyFields bool + // Whether the logger's out is to a terminal isTerminal bool terminalOnce sync.Once @@ -132,7 +135,10 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin } } -func needsQuoting(text string) bool { +func (f *TextFormatter) needsQuoting(text string) bool { + if f.QuoteEmptyFields && len(text) == 0 { + return true + } for _, ch := range text { if !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || @@ -155,14 +161,14 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { switch value := value.(type) { case string: - if !needsQuoting(value) { + if !f.needsQuoting(value) { b.WriteString(value) } else { fmt.Fprintf(b, "%q", value) } case error: errmsg := value.Error() - if !needsQuoting(errmsg) { + if !f.needsQuoting(errmsg) { b.WriteString(errmsg) } else { fmt.Fprintf(b, "%q", errmsg) diff --git a/text_formatter_test.go b/text_formatter_test.go index 107703f..54fc8fe 100644 --- a/text_formatter_test.go +++ b/text_formatter_test.go @@ -3,9 +3,9 @@ package logrus import ( "bytes" "errors" + "strings" "testing" "time" - "strings" ) func TestQuoting(t *testing.T) { @@ -24,6 +24,7 @@ func TestQuoting(t *testing.T) { } } + checkQuoting(false, "") checkQuoting(false, "abcd") checkQuoting(false, "v1.0") checkQuoting(false, "1234567890") @@ -32,6 +33,9 @@ func TestQuoting(t *testing.T) { checkQuoting(true, "x,y") checkQuoting(false, errors.New("invalid")) checkQuoting(true, errors.New("invalid argument")) + + tf.QuoteEmptyFields = true + checkQuoting(true, "") } func TestTimestampFormat(t *testing.T) {