over 3 years ago

Consider contextlib and with Statements for Reusable try/finally Behavior

在講 contextlib.contextmanager ,方便我們實做 context managers

from contextlib import contextmanager

@contextmanager
def log_level(level, name):
    logger = logging.getLogger(name)
    old_level = logger.getEffectiveLevel()
    logger.setLevel(level)
    try:
        yield logger
    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')

logger = logging.getLogger('my-log')
logger.debug('Debug will not print')
logger.error('Error will print')

相關

Python 慣用語 - 15 Context Managers

← Effective Python 心得筆記: Item 42 Effective Python 心得筆記: Item 44 →
 
comments powered by Disqus