Skip to content

Instantly share code, notes, and snippets.

@simon-weber
Created December 8, 2013 03:48
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simon-weber/7853144 to your computer and use it in GitHub Desktop.
Save simon-weber/7853144 to your computer and use it in GitHub Desktop.
A context manager to temporarily disable all logging in Python that supports previous calls to logging.disable.
from contextlib import contextmanager
import logging
@contextmanager
def all_logging_disabled(highest_level=logging.CRITICAL):
"""
A context manager that will prevent any logging messages
triggered during the body from being processed.
:param highest_level: the maximum logging level in use.
This would only need to be changed if a custom level greater than CRITICAL
is defined.
"""
# two kind-of hacks here:
# * can't get the highest logging level in effect => delegate to the user
# * can't get the current module-level override => use an undocumented
# (but non-private!) interface
previous_level = logging.root.manager.disable
logging.disable(highest_level)
try:
yield
finally:
logging.disable(previous_level)
@zrezke
Copy link

zrezke commented Mar 11, 2023

Nice 💯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment