Skip to content

Commit

Permalink
Add ExcludeKey option to TextFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
ningyougang committed May 15, 2024
1 parent dd1b4c2 commit a886e5b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
19 changes: 15 additions & 4 deletions text_formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -320,8 +324,10 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf
if b.Len() > 0 {
b.WriteByte(' ')
}
b.WriteString(key)
b.WriteByte('=')
if !f.ExcludeKey {
b.WriteString(key)
b.WriteByte('=')
}
f.appendValue(b, value)
}

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

if !f.needsQuoting(stringVal) {
// write value without quoting directly when ExcludeKey is true
if f.ExcludeKey {
b.WriteString(stringVal)
} else {
b.WriteString(fmt.Sprintf("%q", stringVal))
if !f.needsQuoting(stringVal) {
b.WriteString(stringVal)
} else {
b.WriteString(fmt.Sprintf("%q", stringVal))
}
}
}
19 changes: 19 additions & 0 deletions text_formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

0 comments on commit a886e5b

Please sign in to comment.