Use % formatting in logging functions and pass the % parameters as
arguments Used when a logging statement has a call form of
“logging.(format_string.format(format_args...))”. Such
calls should use % formatting instead, but leave interpolation to the
logging function by passing the parameters as arguments.

I know I can turn off this warning, but I'd like to understand it. I assumed using format() is the preferred way to print out statements in Python 3. Why is this not true for logger statements?

3 Answers
3

It is not true for logger statement because it relies on former "%" format like string to provide lazy interpolation of this string using extra arguments given to the logger call. For instance instead of doing:

logger.error('oops caused by %s' % exc)

you should do

logger.error('oops caused by %s', exc)

so the string will only be interpolated if the message is actually emitted.

Formatting of message arguments is deferred until it cannot be avoided. However, computing the arguments passed to the logging method can also be expensive, and you may want to avoid doing it if the logger will just throw away your event.

@pfnuesel, .format() is expanded before the call to logger.error, while "lazy interpolation" means expansion is done only if needed (eg the message is actually displayed somewhere)
– sthenaultJan 8 '16 at 9:43

10

Is there a good reference for this lazy evaluation being preferred and making a difference? I couldn't find one in PEP282 or the logging library
– culixMay 6 '16 at 14:48

25

But does this just mean that we will have maintenance problems with our code later? Will we later be "recommended" by pylint to move to the .format() style at some point because logging has upgraded? I ask because I'm more interested in maintainability than I am in bleeding-edge speed performance, at least for most tasks.
– Mike WilliamsonJun 20 '18 at 17:42

3

@MikeWilliamson : I think this message is a warning because there are possible side effects, but you can safely ignore it.
– saihtamtellimNov 29 '18 at 13:38

In my experience a more compelling reason than optimization (for most use cases) for the lazy interpolation is that it plays nicely with log aggregators like Sentry.

Consider a 'user logged in' log message. If you interpolate the user into the format string, you have as many distinct log messages as there are users. If you use lazy interpolation like this, the log aggregator can more reasonably interpret this as the same log message with a bunch of different instances.