#1452·logrus

WithFields will waste computation if the selected logger is disabled

Author: olegbilovusCreated Dec 11, 2024Updated Sep 23, 2025

Example:

go
verbose := flag.Bool("v", false, "verbose")
flag.Parse()

if *verbose {
    log.SetLevel(log.DebugLevel)
}

log.WithFields(log.Fields{
	"a": someComputation(),
	"b": someComputation(),
	"c": someComputation(),
}).Debug("Debug")

When the Debug level is not enabled, WithFields will still be executed but its computation will be ignored later. https://github.com/sirupsen/logrus/blob/d1e6332644483cfee14de11099f03645561d55f8/entry.go#L302-L306

Depending on the specific case, this can slow down a lot the entire program. I had this issue where it was slowing down a lot my program and to avoid such issue I had to wrap the logger with something like this:

go
type Logger struct {
	verbose bool
}

func (l *Logger) Init() {
	if l.verbose {
		logrus.SetLevel(logrus.DebugLevel)
	}
}
func (l *Logger) Debug(fields map[string]interface{}, msg string) {
	if l.verbose {
		logrus.WithFields(fields).Debugln(msg)
	}
}