Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging variables: interpolation or format?

Tags:

python

logging

What is the recommended method for logging variables using Python logging, and why is it better?

Old-style interpolation:

apple = "green"
logger.debug("apple is %s", apple)

or

New-style .format()

logger.debug("apple is {}".format(apple))

I have heard that interpolation is preferred, because it only evaluates the string if it's going to be printed, but I haven’t verified if it actually matters.

like image 904
jonatan Avatar asked Dec 13 '17 16:12

jonatan


1 Answers

logger.debug("apple is {}".format(apple))
logger.debug(f"apple is {apple}")

New-style formatting will always build a string. If this is expensive (e.g. logging a large pandas DataFrame), this will impact performance.


logger.debug("apple is %s", apple)

Old-style interpolation only builds the logging string if the message will actually end up being logged. If you app's loglevel is one of INFO/WARNING/ERROR/CRITICAL, it will only log messages of at least that loglevel. So this DEBUG-level message would not get logged and the interpolation is skipped.

In conclusion, yes, interpolation saves formatting effort (effectively calls to __str__) -- if this actually matters depends on your app.

like image 94
xjcl Avatar answered Oct 12 '22 02:10

xjcl