Skip to content

Commit 6632582

Browse files
Mengqi Yuvincepri
authored andcommitted
🐛 KubeAwareEncoder should handle unstructured object correctly
1 parent c1472c5 commit 6632582

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

pkg/log/zap/kube_helpers.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,9 @@ func (k *KubeAwareEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Fie
105105
// intercept stringer fields that happen to be Kubernetes runtime.Object or
106106
// types.NamespacedName values (Kubernetes runtime.Objects commonly
107107
// implement String, apparently).
108-
if field.Type == zapcore.StringerType {
108+
// *unstructured.Unstructured does NOT implement fmt.Striger interface.
109+
// We have handle it specially.
110+
if field.Type == zapcore.StringerType || field.Type == zapcore.ReflectType {
109111
switch val := field.Interface.(type) {
110112
case runtime.Object:
111113
fields[i] = zapcore.Field{

pkg/log/zap/zap_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
. "github.com/onsi/ginkgo"
2626
. "github.com/onsi/gomega"
2727
kapi "k8s.io/api/core/v1"
28+
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2829
"k8s.io/apimachinery/pkg/types"
2930
)
3031

@@ -238,6 +239,27 @@ var _ = Describe("Zap logger setup", func() {
238239
}))
239240
})
240241

242+
It("should log an unstructured Kubernetes object", func() {
243+
pod := &unstructured.Unstructured{
244+
Object: map[string]interface{}{
245+
"metadata": map[string]interface{}{
246+
"name": "some-pod",
247+
"namespace": "some-ns",
248+
},
249+
},
250+
}
251+
logger.Info("here's a kubernetes object", "thing", pod)
252+
253+
outRaw := logOut.Bytes()
254+
res := map[string]interface{}{}
255+
Expect(json.Unmarshal(outRaw, &res)).To(Succeed())
256+
257+
Expect(res).To(HaveKeyWithValue("thing", map[string]interface{}{
258+
"name": "some-pod",
259+
"namespace": "some-ns",
260+
}))
261+
})
262+
241263
It("should log a standard namespaced NamespacedName name and namespace", func() {
242264
name := types.NamespacedName{Name: "some-pod", Namespace: "some-ns"}
243265
logger.Info("here's a kubernetes object", "thing", name)

0 commit comments

Comments
 (0)