Logger redirect¶
In unittest class, redirect stdout/stderr. Essential for synchronous logging
- class logging_strict.tech_niques.logger_redirect.LoggerRedirector¶
unittestredirectssys.stdoutandsys.stderr. Keep a reference to the real streams so we can later be reverted. Logging goes to the wrong IO streams. Upon failure, there are no log messages.Redirect to the correct IO streams.
Required for the unittest discover command:
--bufferoption- _real_stdout
Hold
sys.stdoutreference. Restores sys.stdout at the end of the context manager
- _real_stderr
Hold
sys.stderrreference. Restores sys.stdout at the end of the context manager
Usage
In a unittest module (level), setup
logging.basicConfig>>> import sys >>> import logging >>> logging.basicConfig( ... format='%(module)s %(levelname)s: %(message)s', ... level=logging.INFO, ... stream=sys.stdout, ... )
In a unittest module class
import sys import logging from logging_strict.tech_niques import LoggerRedirector def setUp(self): # unittest has reassigned sys.stdout and sys.stderr by this point g_module = f"[app_name].tests.test_[module name]" self._LOGGER = logging.getLogger(g_module) # %(asctime)s logging.basicConfig( format="%(levelname)s %(module)s: %(message)s", level=logging.INFO, stream=sys.stdout, ) LoggerRedirector.redirect_loggers( fake_stdout=sys.stdout, fake_stderr=sys.stderr, ) def tearDown(self): # unittest will revert sys.stdout and sys.stderr after this LoggerRedirector.reset_loggers( fake_stdout=sys.stdout, fake_stderr=sys.stderr, )
See also
In unittests, showing log messages on failure
- static all_loggers()¶
Get loggers
- Returns:
space separated tests (method name(s))
- Return type:
Sequence[logging.Logger]
- classmethod redirect_loggers(fake_stdout=None, fake_stderr=None) None¶
unittest temporarily switch the IO streams. Use the unittest temporary IO streams
Call in unittest class setUp method