23 logger.addHandler(file_handler)
24
25 # Log the error message
26 logger.error(f"{exc_type.__name__}: {exc_value}")27
28 # Display an error message to the user
29 print("An error has occurred. Please contact the system administrator.")
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).
import logging
import inspect
logging.basicConfig(level=logging.INFO)
logging.debug(f"Entered function {inspect.stack[0][3]}"))
import logging
import inspect
logging.basicConfig(level=logging.INFO)
logging.debug("Entered function %s", inspect.stack[0][3])