18.8. Logging Optimization

  • isEnabledFor(level)

Formatting of message arguments is deferred until it cannot be avoided. However, computing the arguments passed to the logging method can also be expensive, and you may want to avoid doing it if the logger will just throw away your event. To decide what to do, you can call the isEnabledFor() method which takes a level argument and returns true if the event would be created by the Logger for that level of call. You can write code like this:

>>> import logging
>>> from time import sleep
>>>
>>>
>>> def expensive_function():
...     sleep(10)
>>>
>>>
>>> log = logging.getLogger('myapp')
>>> log.setLevel(logging.INFO)
>>>
>>> log.warning('Start')
>>>
>>> if log.isEnabledFor(logging.DEBUG):
...     log.debug(f'Running debugger... {expensive_function()}')
>>>
>>> log.warning('End')

so that if the logger's threshold is set above DEBUG, the calls to expensive_function() are never made.