Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recover from nil pointers when logging #279

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion klog.go
Expand Up @@ -847,7 +847,7 @@ func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
// (https://github.com/kubernetes/kubernetes/pull/106594#issuecomment-975526235).
switch v := v.(type) {
case fmt.Stringer:
writeStringValue(b, true, v.String())
writeStringValue(b, true, stringerToString(v))
case string:
writeStringValue(b, true, v)
case error:
Expand All @@ -872,6 +872,16 @@ func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
}
}

func stringerToString(s fmt.Stringer) (ret string) {
defer func() {
if err := recover(); err != nil {
ret = "nil"
}
}()
ret = s.String()
return
}

func writeStringValue(b *bytes.Buffer, quote bool, v string) {
data := []byte(v)
index := bytes.IndexByte(data, '\n')
Expand Down
16 changes: 16 additions & 0 deletions klog_test.go
Expand Up @@ -1063,8 +1063,20 @@ func TestErrorS(t *testing.T) {
}
}

// point conforms to fmt.Stringer interface as it implements the String() method
type point struct {
x int
y int
}

// we now have a value receiver
func (p point) String() string {
return fmt.Sprintf("x=%d, y=%d", p.x, p.y)
}

// Test that kvListFormat works as advertised.
func TestKvListFormat(t *testing.T) {
var emptyPoint *point
var testKVList = []struct {
keysValues []interface{}
want string
Expand Down Expand Up @@ -1159,6 +1171,10 @@ No whitespace.`,
})},
want: " pods=[kube-system/kube-dns mi-conf]",
},
{
keysValues: []interface{}{"point-1", point{100, 200}, "point-2", emptyPoint},
want: " point-1=\"x=100, y=200\" point-2=\"nil\"",
},
}

for _, d := range testKVList {
Expand Down