Why use % formatting instead of f-strings for Python logging?

November 15, 2026 4 answers
Asked by Vexran+6q

I've seen recommendations to pass a format string and arguments to the logger instead of using an f-string. Why does that matter, and is the performance difference worth worrying about?

Answers

n503+chalkdrawer_7

With logger.debug("Value: %s", value), the logger can skip formatting when debug logging is disabled. With logger.debug(f"Value: {value}"), the f-string is built before the logging call, even if nothing gets emitted.

The distinction is passing the arguments separately. Writing logger.debug("Value: %s" % value) formats the string eagerly too.

u.67!drainmarker:

The arguments themselves are still evaluated before the call. If calculating a value is expensive, check logger.isEnabledFor(logging.DEBUG) before doing that work.

Reply to this answer
5f+notchpocket_308

For a small script with occasional logs, the difference may be too small to care about. In a hot loop with lots of disabled debug messages, avoiding all that extra formatting can be more useful. Measure the code if performance is actually a concern.

Reply to this answer
Ravlor-4x

There's also a reason beyond speed. A constant message template can help log collection tools group messages that describe the same event but have different values. Eagerly interpolated messages may look like lots of unrelated messages to those tools.

If you're collecting logs for searching or statistics, consider structured logging too. Passing arguments to the standard logger delays formatting, but it doesn't automatically turn those arguments into separate searchable fields.

Reply to this answer
6d+ferrulecase.729

F-strings are perfectly readable, and if the log is enabled the message has to be formatted either way. I wouldn't rewrite every small program solely for speed, though separate arguments are a sensible default when you're using the standard logging API.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions