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

Check if EncodeLevel is set to avoid nil pointer dereference #1058

Merged
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
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