#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from contextlib import contextmanager
from io import StringIO # for handling unicode strings
#==============================================================================
[docs]class MyLogger(logging.getLoggerClass()):
## Expose logging level
DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR
#---------#
# CAPTURE #
#---------#
[docs] def capture_start(self):
"""
Temporary halt the output to its handler, return instance of stringstream to use.
"""
if not getattr(self, '_capstream', None):
capstream = StringIO()
handler = logging.StreamHandler(capstream)
handler.setFormatter(logging.Formatter(u'%(levelname)s: %(funcName)s - %(message)s'))
self._oldhandlers = self.handlers
self._capstream = capstream
self.handlers = [handler]
self._lines = []
return self._lines
[docs] def capture_purge(self):
if hasattr(self, '_capstream'):
dat = self._capstream.getvalue()
self._capstream.truncate(0)
self._lines[:] = dat.replace('\x00','').strip().split('\n')
return None
[docs] def capture_stop(self):
"""Undo the effect of capture above to normal behavior."""
self.handlers = self._oldhandlers
self._capstream.close()
del self._capstream
[docs] @contextmanager
def capture(self):
"""
Usage:
>>> logger = getfixture('logger')
>>> with logger.capture() as lines:
... print('Inside capture')
... logger.info("It should be silent here")
... logger.warning("even if it's very loud.")
Inside capture
>>> for line in lines:
... print(line)
INFO: <module> - It should be silent here
WARNING: <module> - even if it's very loud.
"""
stream = self.capture_start()
yield stream
self.capture_purge()
self.capture_stop()
#==============================================================================