Sam Hooke

Python logging: %s vs format

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

  • It handles tuples more intuitively.
  • It allows using kwargs to more clearly name arguments.
  • It allows using kwargs to reuse arguments in the format string.

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.

These are rough notes from whatever I was working on, interested in or thinking about at the time. They vary greatly in quality and length, but prove useful to me, and hopefully to you too!

← Previous: Escaping Hugo shortcodes within Hugo markdown
Next: Get errno from Python requests `ConnectionError` →