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:
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.