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

Panic of Event.Object() and Event.EmbedObject() with nil #338

Merged
merged 1 commit into from Aug 1, 2021
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
9 changes: 9 additions & 0 deletions event.go
Expand Up @@ -207,6 +207,12 @@ func (e *Event) Object(key string, obj LogObjectMarshaler) *Event {
return e
}
e.buf = enc.AppendKey(e.buf, key)
if obj == nil {
e.buf = enc.AppendNil(e.buf)

return e
}

e.appendObject(obj)
return e
}
Expand All @@ -224,6 +230,9 @@ func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event {
if e == nil {
return e
}
if obj == nil {
return e
}
obj.MarshalZerologObject(e)
return e
}
Expand Down
26 changes: 26 additions & 0 deletions event_test.go
Expand Up @@ -37,3 +37,29 @@ func TestEvent_AnErr(t *testing.T) {
})
}
}

func TestEvent_ObjectWithNil(t *testing.T) {
var buf bytes.Buffer
e := newEvent(levelWriterAdapter{&buf}, DebugLevel)
_ = e.Object("obj", nil)
_ = e.write()

want := `{"obj":null}`
got := strings.TrimSpace(buf.String())
if got != want {
t.Errorf("Event.Object() = %q, want %q", got, want)
}
}

func TestEvent_EmbedObjectWithNil(t *testing.T) {
var buf bytes.Buffer
e := newEvent(levelWriterAdapter{&buf}, DebugLevel)
_ = e.EmbedObject(nil)
_ = e.write()

want := "{}"
got := strings.TrimSpace(buf.String())
if got != want {
t.Errorf("Event.EmbedObject() = %q, want %q", got, want)
}
}