Skip to content

Commit

Permalink
Recover from nil pointers when logging
Browse files Browse the repository at this point in the history
Signed-off-by: Davanum Srinivas <[email protected]>
  • Loading branch information
dims committed Dec 18, 2021
1 parent 9248e72 commit 125dec9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
12 changes: 11 additions & 1 deletion klog.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 125dec9

Please sign in to comment.