From 2f33b9376b8cf2c4ca6bd00ccf248038e2afbdea Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Wed, 18 Mar 2020 01:33:20 +0900 Subject: [PATCH] Add suppress_logging() As a helper for C/C++ domain, this adds suppress_logging(). It works as a context manager and suppresses all loggings during the context temporarily. --- sphinx/util/logging.py | 27 ++++++++++++++++++++++----- tests/test_util_logging.py | 14 ++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/sphinx/util/logging.py b/sphinx/util/logging.py index fb2ec2900..a2dee807d 100644 --- a/sphinx/util/logging.py +++ b/sphinx/util/logging.py @@ -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) diff --git a/tests/test_util_logging.py b/tests/test_util_logging.py index 1581275ee..85646112d 100644 --- a/tests/test_util_logging.py +++ b/tests/test_util_logging.py @@ -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__)