From 18e55c5af9855cb7b3d28f443782eae8ed847fc2 Mon Sep 17 00:00:00 2001 From: Prashant Varanasi Date: Mon, 9 Dec 2019 21:33:16 -0800 Subject: [PATCH] logger: Check level before creating entry Calling `time.Now()` and creating an entry is unnecessary if the underlying core has the specified level disabled. To reduce the cost of logs at disabled levels, skip entry creation if the log level is disabled in the core. This special logic does not apply to DPanic or higher logs as they may need to panic/exit even if the entry does not cause any log to be emitted. On my machine, disabled debugging logs are 6x (~60ns to ~10ns). Fixes #770. --- logger.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/logger.go b/logger.go index dc8f6e3a4..cd6e19551 100644 --- a/logger.go +++ b/logger.go @@ -258,6 +258,12 @@ func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { // (e.g., Check, Info, Fatal). const callerSkipOffset = 2 + // Check the level first to reduce the cost of disabled log calls. + // Since Panic and higher may exit, we skip the optimization for those levels. + if lvl < zapcore.DPanicLevel && !log.core.Enabled(lvl) { + return nil + } + // Create basic checked entry thru the core; this will be non-nil if the // log message will actually be written somewhere. ent := zapcore.Entry{