Merge pull request #3012 from thisch/merge_contextmanagers

Integrate logging_using_handler into catching_logs
This commit is contained in:
Bruno Oliveira 2017-12-13 06:59:48 -02:00 committed by GitHub
commit 38f34e2fa1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 24 deletions

View File

@ -78,23 +78,6 @@ def pytest_addoption(parser):
help='log date format as used by the logging module.') help='log date format as used by the logging module.')
@contextmanager
def logging_using_handler(handler, logger=None):
"""Context manager that safely registers a given handler."""
logger = logger or logging.getLogger(logger)
if handler in logger.handlers: # reentrancy
# Adding the same handler twice would confuse logging system.
# Just don't do that.
yield
else:
logger.addHandler(handler)
try:
yield
finally:
logger.removeHandler(handler)
@contextmanager @contextmanager
def catching_logs(handler, formatter=None, def catching_logs(handler, formatter=None,
level=logging.NOTSET, logger=None): level=logging.NOTSET, logger=None):
@ -105,13 +88,20 @@ def catching_logs(handler, formatter=None,
handler.setFormatter(formatter) handler.setFormatter(formatter)
handler.setLevel(level) handler.setLevel(level)
with logging_using_handler(handler, logger): # Adding the same handler twice would confuse logging system.
orig_level = logger.level # Just don't do that.
logger.setLevel(min(orig_level, level)) add_new_handler = handler not in logger.handlers
try:
yield handler if add_new_handler:
finally: logger.addHandler(handler)
logger.setLevel(orig_level) orig_level = logger.level
logger.setLevel(min(orig_level, level))
try:
yield handler
finally:
logger.setLevel(orig_level)
if add_new_handler:
logger.removeHandler(handler)
class LogCaptureHandler(logging.StreamHandler): class LogCaptureHandler(logging.StreamHandler):