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

json: Don't panic for nil Encode{Time, Duration} #835

Merged
merged 1 commit into from Jun 10, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions zapcore/json_encoder.go
Expand Up @@ -236,7 +236,9 @@ func (enc *jsonEncoder) AppendComplex128(val complex128) {

func (enc *jsonEncoder) AppendDuration(val time.Duration) {
cur := enc.buf.Len()
enc.EncodeDuration(val, enc)
if e := enc.EncodeDuration; e != nil {
e(val, enc)
}
if cur == enc.buf.Len() {
// User-supplied EncodeDuration is a no-op. Fall back to nanoseconds to keep
// JSON valid.
Expand Down Expand Up @@ -275,7 +277,9 @@ func (enc *jsonEncoder) AppendTimeLayout(time time.Time, layout string) {

func (enc *jsonEncoder) AppendTime(val time.Time) {
cur := enc.buf.Len()
enc.EncodeTime(val, enc)
if e := enc.EncodeTime; e != nil {
e(val, enc)
}
if cur == enc.buf.Len() {
// User-supplied EncodeTime is a no-op. Fall back to nanos since epoch to keep
// output JSON valid.
Expand Down
37 changes: 37 additions & 0 deletions zapcore/json_encoder_test.go
Expand Up @@ -129,3 +129,40 @@ func TestJSONEncodeEntry(t *testing.T) {
})
}
}

func TestJSONEmptyConfig(t *testing.T) {
tests := []struct {
name string
field zapcore.Field
expected string
}{
{
name: "time",
field: zap.Time("foo", time.Unix(1591287718, 0)), // 2020-06-04 09:21:58 -0700 PDT
expected: `{"foo": 1591287718000000000}`,
},
{
name: "duration",
field: zap.Duration("bar", time.Microsecond),
expected: `{"bar": 1000}`,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
enc := zapcore.NewJSONEncoder(zapcore.EncoderConfig{})

buf, err := enc.EncodeEntry(zapcore.Entry{
Level: zapcore.DebugLevel,
Time: time.Now(),
LoggerName: "mylogger",
Message: "things happened",
}, []zapcore.Field{tt.field})
if assert.NoError(t, err, "Unexpected JSON encoding error.") {
assert.JSONEq(t, tt.expected, buf.String(), "Incorrect encoded JSON entry.")
}

buf.Free()
})
}
}