From 996d8dcc32b44738a77e4fc5555ce4c82a962a0a Mon Sep 17 00:00:00 2001 From: ffenix113 Date: Wed, 24 Jun 2020 21:30:38 +0200 Subject: [PATCH] Fix UpdateContext panic with empty Context --- log.go | 3 +++ log_test.go | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/log.go b/log.go index cbf68850..d02b15e3 100644 --- a/log.go +++ b/log.go @@ -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 } diff --git a/log_test.go b/log_test.go index 2129bb9d..68ffe56a 100644 --- a/log_test.go +++ b/log_test.go @@ -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) + } +}