Fix UpdateContext panic with empty Context (#244)

This commit is contained in:
Eugene 2020-06-25 01:11:26 +02:00 committed by GitHub
parent 7248ae2fb4
commit 1b763497ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 0 deletions

3
log.go
View File

@ -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
}

View File

@ -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)
}
}