From 77726764eda3d86df495c2759fb8b38b204ec61d Mon Sep 17 00:00:00 2001 From: Olivier Poitrey Date: Fri, 19 May 2017 09:56:31 -0700 Subject: [PATCH] Optimize disabled logging --- README.md | 2 +- log.go | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 90cbd6c..a87ae8a 100644 --- a/README.md +++ b/README.md @@ -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 -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 BenchmarkContextFields-8 10000000 254 ns/op 0 B/op 0 allocs/op BenchmarkLogFields-8 5000000 377 ns/op 0 B/op 0 allocs/op diff --git a/log.go b/log.go index f480bb5..d95d3a5 100644 --- a/log.go +++ b/log.go @@ -69,6 +69,7 @@ package zerolog import ( "io" + "io/ioutil" "os" "sync/atomic" ) @@ -124,6 +125,8 @@ const ( Rarely = 1000 ) +var disabledEvent = newEvent(levelWriterAdapter{ioutil.Discard}, 0, false) + // A Logger represents an active logging object that generates lines // 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 @@ -248,11 +251,15 @@ func (l Logger) Log() Event { } func (l Logger) newEvent(level Level, addLevelField bool, done func(string)) Event { + enabled := l.should(level) + if !enabled { + return disabledEvent + } lvl := InfoLevel if addLevelField { lvl = level } - e := newEvent(l.w, lvl, l.should(level)) + e := newEvent(l.w, lvl, enabled) if addLevelField { e.Str(LevelFieldName, level.String()) }