Use lazy % formatting in logging functions
657 except Exception:
658 logging.exception('Error while charging omise')
659 if charge.failure_code is not None:
660 logging.warning(661 f"Omise Failure Message: {charge.failure_message} ({charge.failure_code})"
662 )
663 return jsonify(
Use lazy % formatting in logging functions
294def resize_speaker_images_task(self, speaker_id, photo_url):
295 speaker = Speaker.query.get(speaker_id)
296 try:
297 logging.info(298 f'Speaker image resizing tasks started for speaker with id {speaker_id}'
299 )
300 uploaded_images = create_save_image_sizes(photo_url, 'speaker-image', speaker_id)
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])