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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With