Fix nil pointer exception on Discard when called with nil logger

Fixes #108
This commit is contained in:
Olivier Poitrey 2018-09-26 09:52:52 -07:00
parent 338f9bc140
commit 20ad1708e7
2 changed files with 18 additions and 0 deletions

View File

@ -92,6 +92,9 @@ func (e *Event) Enabled() bool {
// Discard disables the event so Msg(f) won't print it.
func (e *Event) Discard() *Event {
if e == nil {
return e
}
e.level = Disabled
return nil
}

View File

@ -403,6 +403,21 @@ func TestSampling(t *testing.T) {
}
}
func TestDiscard(t *testing.T) {
out := &bytes.Buffer{}
log := New(out)
log.Log().Discard().Str("a", "b").Msgf("one %s %.1f %d %v", "two", 3.4, 5, errors.New("six"))
if got, want := decodeIfBinaryToString(out.Bytes()), ""; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
// Double call
log.Log().Discard().Discard().Str("a", "b").Msgf("one %s %.1f %d %v", "two", 3.4, 5, errors.New("six"))
if got, want := decodeIfBinaryToString(out.Bytes()), ""; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
}
type levelWriter struct {
ops []struct {
l Level