Fix Output with existing context (fix #20)
Also includes tests for Output()
This commit is contained in:
parent
89e128fdc1
commit
9a65e7ccd2
2
log.go
2
log.go
|
@ -155,8 +155,10 @@ func (l Logger) Output(w io.Writer) Logger {
|
||||||
l2 := New(w)
|
l2 := New(w)
|
||||||
l2.level = l.level
|
l2.level = l.level
|
||||||
l2.sampler = l.sampler
|
l2.sampler = l.sampler
|
||||||
|
if l.context != nil {
|
||||||
l2.context = make([]byte, len(l.context), cap(l.context))
|
l2.context = make([]byte, len(l.context), cap(l.context))
|
||||||
copy(l2.context, l.context)
|
copy(l2.context, l.context)
|
||||||
|
}
|
||||||
return l2
|
return l2
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
28
log_test.go
28
log_test.go
|
@ -406,3 +406,31 @@ func TestEventTimestamp(t *testing.T) {
|
||||||
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue