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

Fix how errors are printed #134

Merged
merged 1 commit into from
Apr 9, 2020
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions klogr/klogr.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ func flatten(kvList ...interface{}) string {
}

func pretty(value interface{}) string {
if err, ok := value.(error); ok {
if _, ok := value.(json.Marshaler); !ok {
value = err.Error()
dims marked this conversation as resolved.
Show resolved Hide resolved
}
}
jb, _ := json.Marshal(value)
return string(jb)
}
Expand Down
29 changes: 29 additions & 0 deletions klogr/klogr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package klogr

import (
"bytes"
"encoding/json"
"errors"
"flag"
"strings"
"testing"

"k8s.io/klog/v2"
Expand Down Expand Up @@ -70,6 +73,20 @@ func TestInfo(t *testing.T) {
text: "test",
keysAndValues: []interface{}{"akey", "avalue", "akey2"},
expectedOutput: ` "msg"="test" "basekey1"="basevar1" "basekey2"=null "akey"="avalue" "akey2"=null
`,
},
"should correctly print regular error types": {
klogr: New().V(0),
text: "test",
keysAndValues: []interface{}{"err", errors.New("whoops")},
expectedOutput: ` "msg"="test" "err"="whoops"
`,
},
"should use MarshalJSON if an error type implements it": {
klogr: New().V(0),
text: "test",
keysAndValues: []interface{}{"err", &customErrorJSON{"whoops"}},
expectedOutput: ` "msg"="test" "err"="WHOOPS"
`,
},
}
Expand All @@ -95,3 +112,15 @@ func TestInfo(t *testing.T) {
})
}
}

type customErrorJSON struct {
s string
}

func (e *customErrorJSON) Error() string {
return e.s
}

func (e *customErrorJSON) MarshalJSON() ([]byte, error) {
return json.Marshal(strings.ToUpper(e.s))
}