18.7. 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.
18.7.1. Assignments
# %% About
# - Name: Logging Optimization isEnabledFor
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Log a debug message 'My message' only if DEBUG level is enabled
# 2. Use `logging` built-in module
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zaloguj komunikat debug 'My message' tylko jeśli poziom DEBUG jest włączony
# 2. Use `logging` built-in module
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# %% Hints
# - `logging.isEnabledFor()`
# - `logging.DEBUG`
# - `logger.debug()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python has an is invalid version; expected: `3.10` or newer.'
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
import logging
# %% Types
# %% Data
log = logging.getLogger('myapp')
# %% Result