Sam Hooke

Python logging: %s vs format

Using format rather than %s syntax for formatting strings in Python has many advantages.

However when it comes to logging, often the reverse is the case.

For example, see the two methods below which produce identical output:

# 1) Percentage string
logger.debug('there are %s lights', lights)

# 2) Format string
logger.debug('there are {} lights'.format(lights))

Reasons to prefer method 1 are:

  • Delayed execution: using the 2nd method, the format function will always be executed; while the 1st method will only actually format the string if that line is executed.
  • Logging aggregator: a log aggregator can tell you that X many instances of that log string occurred in the 1st method, because the log string passed in is always the same; however the second method potentially passes in many different strings, so the log aggregator cannot group them for you.