Skip to content

Commit aedfb7c

Browse files
committed
Add ExcludeKey option to TextFormatter
1 parent dd1b4c2 commit aedfb7c

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

text_formatter.go

+15-4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ func init() {
2828

2929
// TextFormatter formats logs into text
3030
type TextFormatter struct {
31+
// Set to true if want the log not to contain the startingKey, e.g.
32+
// 0001-01-01T00:00:00Z warning message
33+
ExcludeKey bool
34+
3135
// Set to true to bypass checking for a TTY before outputting colors.
3236
ForceColors bool
3337

@@ -320,8 +324,10 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf
320324
if b.Len() > 0 {
321325
b.WriteByte(' ')
322326
}
323-
b.WriteString(key)
324-
b.WriteByte('=')
327+
if !f.ExcludeKey {
328+
b.WriteString(key)
329+
b.WriteByte('=')
330+
}
325331
f.appendValue(b, value)
326332
}
327333

@@ -331,9 +337,14 @@ func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
331337
stringVal = fmt.Sprint(value)
332338
}
333339

334-
if !f.needsQuoting(stringVal) {
340+
// write value without quoting directly when ExcludeKey is true
341+
if f.ExcludeKey {
335342
b.WriteString(stringVal)
336343
} else {
337-
b.WriteString(fmt.Sprintf("%q", stringVal))
344+
if !f.needsQuoting(stringVal) {
345+
b.WriteString(stringVal)
346+
} else {
347+
b.WriteString(fmt.Sprintf("%q", stringVal))
348+
}
338349
}
339350
}

text_formatter_test.go

+19
Original file line numberDiff line numberDiff line change
@@ -598,3 +598,22 @@ func TestCustomSorting(t *testing.T) {
598598
require.NoError(t, err)
599599
require.True(t, strings.HasPrefix(string(b), "prefix="), "format output is %q", string(b))
600600
}
601+
602+
func TestFormattingNotIncludeStartingKey(t *testing.T) {
603+
tf := &TextFormatter{ExcludeKey: true}
604+
605+
testCases := []struct {
606+
value string
607+
expected string
608+
}{
609+
{`foo`, "0001-01-01T00:00:00Z panic foo\n"},
610+
}
611+
612+
for _, tc := range testCases {
613+
b, _ := tf.Format(WithField("test", tc.value))
614+
615+
if string(b) != tc.expected {
616+
t.Errorf("formatting expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
617+
}
618+
}
619+
}

0 commit comments

Comments
 (0)