Created
September 26, 2023 10:20
-
-
Save nenetto/5c98cf2e75fc1f4719356fbeba6e6c87 to your computer and use it in GitHub Desktop.
Contextlib and with
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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