Skip to content

Commit

Permalink
structured logging: avoid quoting of strings with line breaks
Browse files Browse the repository at this point in the history
It makes the output harder to read, in particular when the string is long (see
kubernetes/kubernetes#104868).

The revised handling of key/value pairs will produce the following output for
two key/value pairs where the first one has a multi-line string as value:

 multiLineString=vvvvv string vvvvv
 Hello world!
 	Starts with tab.
   Starts with spaces.
 No whitespace.
 ^^^^^ string ^^^^^
 pod="kubedns"
  • Loading branch information
pohly committed Nov 9, 2021
1 parent 9ad2462 commit 1f31c16
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
24 changes: 20 additions & 4 deletions klog.go
Original file line number Diff line number Diff line change
Expand Up @@ -824,21 +824,37 @@ func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
}
b.WriteByte(' ')

switch v.(type) {
case string, error:
switch v := v.(type) {
case string:
writeStringValue(b, k, v)
case error:
b.WriteString(fmt.Sprintf("%s=%q", k, v))
case []byte:
b.WriteString(fmt.Sprintf("%s=%+q", k, v))
default:
if _, ok := v.(fmt.Stringer); ok {
b.WriteString(fmt.Sprintf("%s=%q", k, v))
if s, ok := v.(fmt.Stringer); ok {
writeStringValue(b, k, s.String())
} else {
b.WriteString(fmt.Sprintf("%s=%+v", k, v))
}
}
}
}

func writeStringValue(b *bytes.Buffer, k interface{}, v string) {
if !strings.Contains(v, "\n") {
// Simple string, quote quotation marks and non-printable characters.
b.WriteString(fmt.Sprintf("%s=%q", k, v))
return
}
// Complex multi-line string, show as-is with indention.
b.WriteString(fmt.Sprintf("%s=vvvvv string vvvvv\n", k))
for _, line := range strings.Split(v, "\n") {
b.WriteString(" " + line + "\n")
}
b.WriteString(" ^^^^^ string ^^^^^")
}

// redirectBuffer is used to set an alternate destination for the logs
type redirectBuffer struct {
w io.Writer
Expand Down
14 changes: 14 additions & 0 deletions klog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,20 @@ func TestKvListFormat(t *testing.T) {
keysValues: []interface{}{"pod", "kubedns", "bytes", []byte("��=� ⌘")},
want: " pod=\"kubedns\" bytes=\"\\ufffd\\ufffd=\\ufffd \\u2318\"",
},
{
keysValues: []interface{}{"multiLineString", `Hello world!
Starts with tab.
Starts with spaces.
No whitespace.`,
"pod", "kubedns",
},
want: ` multiLineString=vvvvv string vvvvv
Hello world!
Starts with tab.
Starts with spaces.
No whitespace.
^^^^^ string ^^^^^ pod="kubedns"`,
},
{
keysValues: []interface{}{"pod", "kubedns", "maps", map[string]int{"three": 4}},
want: " pod=\"kubedns\" maps=map[three:4]",
Expand Down

0 comments on commit 1f31c16

Please sign in to comment.