George V. Reilly

Logging in Python: Don't use new-fangled format

Python 2.6 introduced the format method to strings. In general, format is now the preferred way to build strings instead of the old % formatting operator.

One exception is with the logging module, where the best practice is to use %s and %d. Why? First, %s is the idiomatic way to use logging, which was built years before format was introduced. Second, if there’s a literal % in the in­ter­po­lat­ed values, logging will be unhappy, since there won’t be cor­re­spond­ing arguments in the call. It won’t fall over, since “The logging package is designed to swallow exceptions which occur while logging in production. This is so that errors which occur while handling logging events - such as logging mis­con­fig­u­ra­tion, network or other similar errors - do not cause the ap­pli­ca­tion using logging to terminate pre­ma­ture­ly.”

In other systems, an un­con­trolled format string can lead to serious vul­ner­a­bil­i­ties.

TL;DR, write:

logging.info("Report: Processing %d annotations for id %s",
            len(annotations), report_id)

not:

logging.info("Report: Processing {} annotations for id {}".format(
            len(annotations), report_id))
blog comments powered by Disqus
Review: Flashman and the Mountain of Light » « Python: Joining URLs with posixpath.join