Use lazy % formatting in logging functions
78 logging.info(" Drone Script ")
79 logging.info("--------------------------------------")
80
81 logging.debug(f"Current port for UDP connection: {str(port)}") 82
83 logging.info(" Checking network... \r\n")
84 time.sleep(0.5)
Description
Formatting the message manually before passing it to a logging
call does unnecessary work if logging is disabled. Consider using the logging
module's built-in formatting features to avoid that.
If your logging level is set to "WARNING"
, but the logging call is:
logging.debug("Data: %s", data)
In the above example, there will be no logging as the level debug
is below warning
. The conversion of the data
object to a string will be skipped by the logging module resulting in improved performance.
logging.debug(f"Data: {data}")
In the code shown above, the conversion of the data
object to a string will happen regardless of whether the message is logged or not (which is based on the log level).
Bad practice
import logging
import inspect
logging.basicConfig(level=logging.INFO)
logging.debug(f"Entered function {inspect.stack[0][3]}"))
Recommended
import logging
import inspect
logging.basicConfig(level=logging.INFO)
logging.debug("Entered function %s", inspect.stack[0][3])