Optimize disabled logging

This commit is contained in:
Olivier Poitrey 2017-05-19 09:56:31 -07:00
parent a417fb1a8b
commit 77726764ed
2 changed files with 9 additions and 2 deletions

View File

@ -16,7 +16,7 @@ All operations are allocation free (those numbers *include* JSON encoding):
``` ```
BenchmarkLogEmpty-8 50000000 22 ns/op 0 B/op 0 allocs/op BenchmarkLogEmpty-8 50000000 22 ns/op 0 B/op 0 allocs/op
BenchmarkDisabled-8 100000000 10 ns/op 0 B/op 0 allocs/op BenchmarkDisabled-8 100000000 9 ns/op 0 B/op 0 allocs/op
BenchmarkInfo-8 10000000 210 ns/op 0 B/op 0 allocs/op BenchmarkInfo-8 10000000 210 ns/op 0 B/op 0 allocs/op
BenchmarkContextFields-8 10000000 254 ns/op 0 B/op 0 allocs/op BenchmarkContextFields-8 10000000 254 ns/op 0 B/op 0 allocs/op
BenchmarkLogFields-8 5000000 377 ns/op 0 B/op 0 allocs/op BenchmarkLogFields-8 5000000 377 ns/op 0 B/op 0 allocs/op

9
log.go
View File

@ -69,6 +69,7 @@ package zerolog
import ( import (
"io" "io"
"io/ioutil"
"os" "os"
"sync/atomic" "sync/atomic"
) )
@ -124,6 +125,8 @@ const (
Rarely = 1000 Rarely = 1000
) )
var disabledEvent = newEvent(levelWriterAdapter{ioutil.Discard}, 0, false)
// A Logger represents an active logging object that generates lines // A Logger represents an active logging object that generates lines
// of JSON output to an io.Writer. Each logging operation makes a single // of JSON output to an io.Writer. Each logging operation makes a single
// call to the Writer's Write method. There is no guaranty on access // call to the Writer's Write method. There is no guaranty on access
@ -248,11 +251,15 @@ func (l Logger) Log() Event {
} }
func (l Logger) newEvent(level Level, addLevelField bool, done func(string)) Event { func (l Logger) newEvent(level Level, addLevelField bool, done func(string)) Event {
enabled := l.should(level)
if !enabled {
return disabledEvent
}
lvl := InfoLevel lvl := InfoLevel
if addLevelField { if addLevelField {
lvl = level lvl = level
} }
e := newEvent(l.w, lvl, l.should(level)) e := newEvent(l.w, lvl, enabled)
if addLevelField { if addLevelField {
e.Str(LevelFieldName, level.String()) e.Str(LevelFieldName, level.String())
} }