Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
olegbilovus opened this issue Dec 11, 2024 · 0 comments
Open

Comments

@olegbilovus
Copy link

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)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant