Logger redirect

In unittest class, redirect stdout/stderr. Essential for synchronous logging

class logging_strict.tech_niques.logger_redirect.LoggerRedirector

unittest redirects sys.stdout and sys.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: --buffer option

_real_stdout

Hold sys.stdout reference. Restores sys.stdout at the end of the context manager

_real_stderr

Hold sys.stderr reference. 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

LoggerRedirector source

LoggerRedirector author

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

Parameters:
  • fake_stdout (TextIO) – unittest temporary stdout IO stream

  • fake_stderr (TextIO) – unittest temporary stderr IO stream

classmethod reset_loggers(fake_stdout=None, fake_stderr=None) None

unittest temporarily switch the IO streams. Switch back to the normal IO streams

Call in unittest class tearDown method

Parameters:
  • fake_stdout (TextIO) – unittest temporary stdout IO stream

  • fake_stderr (TextIO) – unittest temporary stderr IO stream