Fix Output with existing context (fix #20)

Also includes tests for Output()
This commit is contained in:
Ravi Raju 2017-11-08 10:47:56 -08:00 committed by Olivier Poitrey
parent 89e128fdc1
commit 9a65e7ccd2
2 changed files with 32 additions and 2 deletions

2
log.go
View File

@ -155,8 +155,10 @@ func (l Logger) Output(w io.Writer) Logger {
l2 := New(w)
l2.level = l.level
l2.sampler = l.sampler
if l.context != nil {
l2.context = make([]byte, len(l.context), cap(l.context))
copy(l2.context, l.context)
}
return l2
}

View File

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