Add ExcludeKey option to TextFormatter

This commit is contained in:
甯尤刚[C&N Dev] 2024-05-14 02:00:24 -04:00
parent dd1b4c2e81
commit a886e5b0f8
2 changed files with 34 additions and 4 deletions

View File

@ -28,6 +28,10 @@ func init() {
// TextFormatter formats logs into text
type TextFormatter struct {
// Set to true if want the log not to contain the startingKey, e.g.
// 0001-01-01T00:00:00Z warning message
ExcludeKey bool
// Set to true to bypass checking for a TTY before outputting colors.
ForceColors bool
@ -320,8 +324,10 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf
if b.Len() > 0 {
b.WriteByte(' ')
}
if !f.ExcludeKey {
b.WriteString(key)
b.WriteByte('=')
}
f.appendValue(b, value)
}
@ -331,9 +337,14 @@ func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
stringVal = fmt.Sprint(value)
}
// write value without quoting directly when ExcludeKey is true
if f.ExcludeKey {
b.WriteString(stringVal)
} else {
if !f.needsQuoting(stringVal) {
b.WriteString(stringVal)
} else {
b.WriteString(fmt.Sprintf("%q", stringVal))
}
}
}

View File

@ -598,3 +598,22 @@ func TestCustomSorting(t *testing.T) {
require.NoError(t, err)
require.True(t, strings.HasPrefix(string(b), "prefix="), "format output is %q", string(b))
}
func TestFormattingNotContainStartingKey(t *testing.T) {
tf := &TextFormatter{ExcludeKey: true}
testCases := []struct {
value string
expected string
}{
{`foo`, "0001-01-01T00:00:00Z panic foo\n"},
}
for _, tc := range testCases {
b, _ := tf.Format(WithField("test", tc.value))
if string(b) != tc.expected {
t.Errorf("formatting expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
}
}
}