Skip to content

Instantly share code, notes, and snippets.

@nenetto
Created September 26, 2023 10:20
Show Gist options
  • Save nenetto/5c98cf2e75fc1f4719356fbeba6e6c87 to your computer and use it in GitHub Desktop.
Save nenetto/5c98cf2e75fc1f4719356fbeba6e6c87 to your computer and use it in GitHub Desktop.
Contextlib and with
@contextmanager
def debug_logging(level):
""" Change the logging level
"""
logger = logging.getLogger()
old_level = logger.getEffectiveLevel()
logger.setLevel(level)
try:
yield
finally:
logger.setLevel(old_level)
# Example
with debug_logging(logging.DEBUG):
print(‘Inside:’)
my_function()
print(‘After:’)
my_function()
## Using Targets (yields inside context managers)
@contextmanager
def log_level(level, name):
logger = logging.getLogger(name)
old_level = logger.getEffectiveLevel()
logger.setLevel(level)
try:
yield logger # This is the main difference
finally:
logger.setLevel(old_level)
with log_level(logging.DEBUG, 'my-log') as logger:
logger.debug('This is my message!')
logging.debug('This will not print')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment