Skip to content

WithFields will waste computation if the selected logger is disabled #1452

@olegbilovus

Description

@olegbilovus

Example:

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.

logrus/entry.go

Lines 302 to 306 in d1e6332

func (entry *Entry) Log(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.log(level, fmt.Sprint(args...))
}
}

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:

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)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions