Skip to content

Instantly share code, notes, and snippets.

@Kerrigan29a
Created May 28, 2015 11:50
Show Gist options
  • Save Kerrigan29a/1c281e2fd6cf4b4de4f6 to your computer and use it in GitHub Desktop.
Save Kerrigan29a/1c281e2fd6cf4b4de4f6 to your computer and use it in GitHub Desktop.
How to redirect unittest stream to the logging module
class Stream2Logger(object):
def __init__(self, stream, logger, level):
self._stream = stream
self._logger = logger
self._level = level
self._buffer = []
def write(self, message):
self._buffer.append(message)
if "\n" in message:
self.flush()
def flush(self):
if self._buffer:
message = "".join(self._buffer)
if "\n" in message:
self._logger.log(self._level, message.rstrip())
self._buffer = []
else:
self._buffer = [message]
if __name__ == '__main__':
suite = unittest.TestSuite()
# suite.addTest(...)
logger = logging.getLogger('dummmy')
stream = Stream2Logger(sys.stderr, logger, logging.ERROR)
unittest.TextTestRunner(stream=stream, verbosity=2).run(suite)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment