Skip to content

Commit

Permalink
pkg/log: improve performance for disabled log levels (scionproto#4304)
Browse files Browse the repository at this point in the history
Check if the log level is enabled before converting the log data
with a call to convertCtx, to reduce the cost of the log call for
disabled log levels.

The following benchmark tests shows an improvement of the execution time
from 135ns to 30ns with this change.

```go
func BenchmarkLog(b *testing.B) {
	err := log.Setup(log.Config{Console: log.ConsoleConfig{Level: "info"}})
	assert.NoError(b, err)
	for i := 0; i < b.N; i++ {
		log.Debug("hello world", "i", i)
	}
}
```
  • Loading branch information
rohrerj authored and benthor committed Jan 23, 2023
1 parent 3d3db02 commit d6332e2
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions pkg/log/wrappers.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,27 @@ import (

// Debug logs at debug level.
func Debug(msg string, ctx ...interface{}) {
zap.L().Debug(msg, convertCtx(ctx)...)
if enabled(DebugLevel) {
zap.L().Debug(msg, convertCtx(ctx)...)
}
}

// Info logs at info level.
func Info(msg string, ctx ...interface{}) {
zap.L().Info(msg, convertCtx(ctx)...)
if enabled(InfoLevel) {
zap.L().Info(msg, convertCtx(ctx)...)
}
}

// Error logs at error level.
func Error(msg string, ctx ...interface{}) {
zap.L().Error(msg, convertCtx(ctx)...)
if enabled(ErrorLevel) {
zap.L().Error(msg, convertCtx(ctx)...)
}
}

func enabled(lvl Level) bool {
return zap.L().Core().Enabled(zapcore.Level(lvl))
}

// WithOptions returns the logger with the options applied.
Expand Down Expand Up @@ -72,15 +82,21 @@ func (l *logger) New(ctx ...interface{}) Logger {
}

func (l *logger) Debug(msg string, ctx ...interface{}) {
l.logger.Debug(msg, convertCtx(ctx)...)
if l.Enabled(DebugLevel) {
l.logger.Debug(msg, convertCtx(ctx)...)
}
}

func (l *logger) Info(msg string, ctx ...interface{}) {
l.logger.Info(msg, convertCtx(ctx)...)
if l.Enabled(InfoLevel) {
l.logger.Info(msg, convertCtx(ctx)...)
}
}

func (l *logger) Error(msg string, ctx ...interface{}) {
l.logger.Error(msg, convertCtx(ctx)...)
if l.Enabled(ErrorLevel) {
l.logger.Error(msg, convertCtx(ctx)...)
}
}

func (l *logger) Enabled(lvl Level) bool {
Expand Down

0 comments on commit d6332e2

Please sign in to comment.