Add 'QuoteEmptyFields' option to TextFormatter

This commit is contained in:
Ben Brooks 2017-02-14 10:53:03 +00:00
parent 3f603f494d
commit cfca98e6d9
No known key found for this signature in database
GPG Key ID: F2C8424D997DE166
2 changed files with 14 additions and 4 deletions

View File

@ -49,6 +49,9 @@ type TextFormatter struct {
// be desired. // be desired.
DisableSorting bool DisableSorting bool
// QuoteEmptyFields will wrap empty fields in quotes if true
QuoteEmptyFields bool
// Whether the logger's out is to a terminal // Whether the logger's out is to a terminal
isTerminal bool isTerminal bool
terminalOnce sync.Once 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 { for _, ch := range text {
if !((ch >= 'a' && ch <= 'z') || if !((ch >= 'a' && ch <= 'z') ||
(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{}) { func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
switch value := value.(type) { switch value := value.(type) {
case string: case string:
if !needsQuoting(value) { if !f.needsQuoting(value) {
b.WriteString(value) b.WriteString(value)
} else { } else {
fmt.Fprintf(b, "%q", value) fmt.Fprintf(b, "%q", value)
} }
case error: case error:
errmsg := value.Error() errmsg := value.Error()
if !needsQuoting(errmsg) { if !f.needsQuoting(errmsg) {
b.WriteString(errmsg) b.WriteString(errmsg)
} else { } else {
fmt.Fprintf(b, "%q", errmsg) fmt.Fprintf(b, "%q", errmsg)

View File

@ -3,9 +3,9 @@ package logrus
import ( import (
"bytes" "bytes"
"errors" "errors"
"strings"
"testing" "testing"
"time" "time"
"strings"
) )
func TestQuoting(t *testing.T) { func TestQuoting(t *testing.T) {
@ -24,6 +24,7 @@ func TestQuoting(t *testing.T) {
} }
} }
checkQuoting(false, "")
checkQuoting(false, "abcd") checkQuoting(false, "abcd")
checkQuoting(false, "v1.0") checkQuoting(false, "v1.0")
checkQuoting(false, "1234567890") checkQuoting(false, "1234567890")
@ -32,6 +33,9 @@ func TestQuoting(t *testing.T) {
checkQuoting(true, "x,y") checkQuoting(true, "x,y")
checkQuoting(false, errors.New("invalid")) checkQuoting(false, errors.New("invalid"))
checkQuoting(true, errors.New("invalid argument")) checkQuoting(true, errors.New("invalid argument"))
tf.QuoteEmptyFields = true
checkQuoting(true, "")
} }
func TestTimestampFormat(t *testing.T) { func TestTimestampFormat(t *testing.T) {