How to format strings for logging in Python
summary
Claim: f-strings are fastest when messages are emitted but percent-style logging defers formatting when a message is suppressed. Timing examples show ~890 µs vs ~990 µs when printed and 280 ns vs 500 ns when suppressed, so absolute differences are tiny. Demonstration uses Python logging module and microbenchmarks. Security example shows crafted format padding can produce one gigabyte of whitespace and freeze a program. Recommendation: prefer f-strings for readability, use deferred formatting or validate untrusted format strings for safety.
AI-written summary · about
related talks
20mPEP 498: The Monologue
24mF Strings!
19mPython - best practices
11mUsing and abusing Python's logging module for more readable logs
35mText Is Not Text: The History of Strings in Python
11mUsing and abusing Python's logging module for more readable logs
32mProfiling at the speed of light
21mlogger.info(f"Don't Give all your {secrets} away")
