Skip to content

Commit 125dec9

Browse files
committed
Recover from nil pointers when logging
Signed-off-by: Davanum Srinivas <[email protected]>
1 parent 9248e72 commit 125dec9

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

klog.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -847,7 +847,7 @@ func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
847847
// (https://github.com/kubernetes/kubernetes/pull/106594#issuecomment-975526235).
848848
switch v := v.(type) {
849849
case fmt.Stringer:
850-
writeStringValue(b, true, v.String())
850+
writeStringValue(b, true, stringerToString(v))
851851
case string:
852852
writeStringValue(b, true, v)
853853
case error:
@@ -872,6 +872,16 @@ func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
872872
}
873873
}
874874

875+
func stringerToString(s fmt.Stringer) (ret string) {
876+
defer func() {
877+
if err := recover(); err != nil {
878+
ret = "nil"
879+
}
880+
}()
881+
ret = s.String()
882+
return
883+
}
884+
875885
func writeStringValue(b *bytes.Buffer, quote bool, v string) {
876886
data := []byte(v)
877887
index := bytes.IndexByte(data, '\n')

klog_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -1063,8 +1063,20 @@ func TestErrorS(t *testing.T) {
10631063
}
10641064
}
10651065

1066+
// point conforms to fmt.Stringer interface as it implements the String() method
1067+
type point struct {
1068+
x int
1069+
y int
1070+
}
1071+
1072+
// we now have a value receiver
1073+
func (p point) String() string {
1074+
return fmt.Sprintf("x=%d, y=%d", p.x, p.y)
1075+
}
1076+
10661077
// Test that kvListFormat works as advertised.
10671078
func TestKvListFormat(t *testing.T) {
1079+
var emptyPoint *point
10681080
var testKVList = []struct {
10691081
keysValues []interface{}
10701082
want string
@@ -1159,6 +1171,10 @@ No whitespace.`,
11591171
})},
11601172
want: " pods=[kube-system/kube-dns mi-conf]",
11611173
},
1174+
{
1175+
keysValues: []interface{}{"point-1", point{100, 200}, "point-2", emptyPoint},
1176+
want: " point-1=\"x=100, y=200\" point-2=\"nil\"",
1177+
},
11621178
}
11631179

11641180
for _, d := range testKVList {

0 commit comments

Comments
 (0)