Avoid extra quotes where not strictly necessary.
It's not necessary to enclose in quotes every single string value
in log2met format; when using basic words, it's possible to not
quote it (as heroku does for its own logging). This keeps the
logs easier on the human eye.
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 @@
import (
"bytes"
"fmt"
+ "regexp"
"sort"
"strings"
"time"
@@ -19,11 +20,13 @@
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 (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"))
+}