import logging
logging.basicConfig(level=logging.INFO)
name = "world"
logging.debug(f"hello {world}") # Non Compliant: the replacement will be done immediately but will not be printed because current level is INFO
When logging with formatted string, prefer using %s and logging kwargs which will be deferred until it cannot be avoided, instead of immediate .format() or f"" interpolation.
import logging
logging.basicConfig(level=logging.INFO)
name = "world"
logging.debug(f"hello {world}") # Non Compliant: the replacement will be done immediately but will not be printed because current level is INFO
import logging
logging.basicConfig(level=logging.INFO)
name = "world"
logging.debug("hello %s", name) # Compliant: the replacement will be avoided by logging module because it is not necessary
This rule is relevant to logging formatting. Using logging kwargs is more efficient than immediate builtin formatting.
Processor: Intel® Core™ i5-2520M CPU @ 2.50GHz, 4 cores
RAM: 8 GB
CO2 Emissions Measurement: Using CodeCarbon
Two approaches were benchmarked:
- Non-compliant: Using logging with .format()
- Compliant: Using logging with %s and kwargs
Replacing f"" and "".format() with %s and logging kwargs permits to defer template replacement when the log is not displayed.