Skip to content

Commit

Permalink
json: Don't panic for nil Encode{Time, Duration} (uber-go#835)
Browse files Browse the repository at this point in the history
Fixes uber-go#834

The JSON encoder assumes that encoders for `time.Time` and
`time.Duration` are always specified, which causes nil pointer
dereference panics.

Fix this by treating nil encoders for time and duration as no-ops. This
will fall back to existing logic in the JSON encoder that handles no-op
time and duration encoders.
  • Loading branch information
abhinav authored Jun 10, 2020
1 parent 3d39773 commit 981f1de
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
8 changes: 6 additions & 2 deletions zapcore/json_encoder.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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()
})
}
}

0 comments on commit 981f1de

Please sign in to comment.