Merge pull request #7327 from tk0miya/suppress_logging

Add suppress_logging()
This commit is contained in:
Jakob Lykke Andersen 2020-03-17 18:33:37 +01:00 committed by GitHub
commit cb0f33eb8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 5 deletions

View File

@ -220,16 +220,15 @@ def pending_warnings() -> Generator[logging.Handler, None, None]:
@contextmanager
def pending_logging() -> Generator[MemoryHandler, None, None]:
"""Contextmanager to pend logging all logs temporary.
def suppress_logging() -> Generator[MemoryHandler, None, None]:
"""Contextmanager to suppress logging all logs temporary.
For example::
>>> with pending_logging():
>>> logger.warning('Warning message!') # not flushed yet
>>> with suppress_logging():
>>> logger.warning('Warning message!') # suppressed
>>> some_long_process()
>>>
Warning message! # the warning is flushed here
"""
logger = logging.getLogger(NAMESPACE)
memhandler = MemoryHandler()
@ -248,6 +247,24 @@ def pending_logging() -> Generator[MemoryHandler, None, None]:
for handler in handlers:
logger.addHandler(handler)
@contextmanager
def pending_logging() -> Generator[MemoryHandler, None, None]:
"""Contextmanager to pend logging all logs temporary.
For example::
>>> with pending_logging():
>>> logger.warning('Warning message!') # not flushed yet
>>> some_long_process()
>>>
Warning message! # the warning is flushed here
"""
logger = logging.getLogger(NAMESPACE)
try:
with suppress_logging() as memhandler:
yield memhandler
finally:
memhandler.flushTo(logger)

View File

@ -233,6 +233,20 @@ def test_warning_location(app, status, warning):
assert colorize('red', 'WARNING: message7') in warning.getvalue()
def test_suppress_logging(app, status, warning):
logging.setup(app, status, warning)
logger = logging.getLogger(__name__)
logger.warning('message1')
with logging.suppress_logging():
logger.warning('message2')
assert 'WARNING: message1' in warning.getvalue()
assert 'WARNING: message2' not in warning.getvalue()
assert 'WARNING: message1' in warning.getvalue()
assert 'WARNING: message2' not in warning.getvalue()
def test_pending_warnings(app, status, warning):
logging.setup(app, status, warning)
logger = logging.getLogger(__name__)