Merge pull request #3012 from thisch/merge_contextmanagers
Integrate logging_using_handler into catching_logs
This commit is contained in:
commit
38f34e2fa1
|
@ -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):
|
||||||
|
|
Loading…
Reference in New Issue