Skip to content

Commit

Permalink
JSON Encoder: Don't panic if EncodeLevel unset (#1058)
Browse files Browse the repository at this point in the history
The JSON Encoder currently panics during EncodeEntry if the EncodeLevel
option is unset.
Fix this by adding a nil check for it.
This mirrors the behavior of the Console Encoder.
  • Loading branch information
aerosol authored Feb 4, 2022
1 parent a1155d9 commit a7613b2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion zapcore/json_encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ func (enc *jsonEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer,
final := enc.clone()
final.buf.AppendByte('{')

if final.LevelKey != "" {
if final.LevelKey != "" && final.EncodeLevel != nil {
final.addKey(final.LevelKey)
cur := final.buf.Len()
final.EncodeLevel(ent.Level, final)
Expand Down
29 changes: 29 additions & 0 deletions zapcore/json_encoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,35 @@ func TestJSONEncodeEntry(t *testing.T) {
}
}

func TestNoEncodeLevelSupplied(t *testing.T) {
enc := zapcore.NewJSONEncoder(zapcore.EncoderConfig{
MessageKey: "M",
LevelKey: "L",
TimeKey: "T",
NameKey: "N",
CallerKey: "C",
FunctionKey: "F",
StacktraceKey: "S",
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
})

ent := zapcore.Entry{
Level: zapcore.InfoLevel,
Time: time.Date(2018, 6, 19, 16, 33, 42, 99, time.UTC),
LoggerName: "bob",
Message: "lob law",
}

fields := []zapcore.Field{
zap.Int("answer", 42),
}

_, err := enc.EncodeEntry(ent, fields)
assert.NoError(t, err, "Unexpected JSON encoding error.")
}

func TestJSONEmptyConfig(t *testing.T) {
tests := []struct {
name string
Expand Down

0 comments on commit a7613b2

Please sign in to comment.