From 9a65e7ccd2bad9082586a4de21f914648416c90f Mon Sep 17 00:00:00 2001 From: Ravi Raju Date: Wed, 8 Nov 2017 10:47:56 -0800 Subject: [PATCH] Fix Output with existing context (fix #20) Also includes tests for Output() --- log.go | 6 ++++-- log_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/log.go b/log.go index a9b4121..66c8410 100644 --- a/log.go +++ b/log.go @@ -155,8 +155,10 @@ func (l Logger) Output(w io.Writer) Logger { l2 := New(w) l2.level = l.level l2.sampler = l.sampler - l2.context = make([]byte, len(l.context), cap(l.context)) - copy(l2.context, l.context) + if l.context != nil { + l2.context = make([]byte, len(l.context), cap(l.context)) + copy(l2.context, l.context) + } return l2 } diff --git a/log_test.go b/log_test.go index a5a51e5..ed9e498 100644 --- a/log_test.go +++ b/log_test.go @@ -406,3 +406,31 @@ func TestEventTimestamp(t *testing.T) { t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want) } } + +func TestOutputWithoutTimestamp(t *testing.T) { + ignoredOut := &bytes.Buffer{} + out := &bytes.Buffer{} + log := New(ignoredOut).Output(out).With().Str("foo", "bar").Logger() + log.Log().Msg("hello world") + + if got, want := out.String(), `{"foo":"bar","message":"hello world"}`+"\n"; got != want { + t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want) + } +} + +func TestOutputWithTimestamp(t *testing.T) { + TimestampFunc = func() time.Time { + return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC) + } + defer func() { + TimestampFunc = time.Now + }() + ignoredOut := &bytes.Buffer{} + out := &bytes.Buffer{} + log := New(ignoredOut).Output(out).With().Timestamp().Str("foo", "bar").Logger() + log.Log().Msg("hello world") + + if got, want := out.String(), `{"time":"2001-02-03T04:05:06Z","foo":"bar","message":"hello world"}`+"\n"; got != want { + t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want) + } +}