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

Fix UpdateContext panic with empty Context #244

Merged
merged 1 commit into from Jun 24, 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
3 changes: 3 additions & 0 deletions log.go
Expand Up @@ -252,6 +252,9 @@ func (l *Logger) UpdateContext(update func(c Context) Context) {
if cap(l.context) == 0 {
l.context = make([]byte, 0, 500)
}
if len(l.context) == 0 {
l.context = enc.AppendBeginMarker(l.context)
}
c := update(Context{*l})
l.context = c.l.context
}
Expand Down
16 changes: 16 additions & 0 deletions log_test.go
Expand Up @@ -772,3 +772,19 @@ func TestErrorHandler(t *testing.T) {
t.Errorf("ErrorHandler err = %#v, want %#v", got, want)
}
}

func TestUpdateEmptyContext(t *testing.T) {
var buf bytes.Buffer
log := New(&buf)

log.UpdateContext(func(c Context) Context {
return c.Str("foo", "bar")
})
log.Info().Msg("no panic")

want := `{"level":"info","foo":"bar","message":"no panic"}` + "\n"

if got := buf.String(); got != want {
t.Errorf("invalid log output:\ngot: %q\nwant: %q", got, want)
}
}