Created
June 5, 2014 13:57
-
-
Save boris317/22ee2d6f1e5f15996cf2 to your computer and use it in GitHub Desktop.
Context manager for testing log output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import logging | |
| from contextlib import contextmanager | |
| from cStringIO import StringIO | |
| @contextmanager | |
| def log_context(logger_name, level=logging.DEBUG, formatter=None): | |
| """ | |
| :param logger_name: Name of your logger as passed to ``logging.getLogger``. | |
| :param level: (optional) logging level to capture. | |
| :param formatter: (optional) logging.Formatter to use. | |
| Use this context manager to help test log output. Suppose you have an app | |
| that is required to log some of data. We could create a test for that like | |
| this :: | |
| # unittest method | |
| def test_log_output(self) | |
| with log_context("app-logger") as log: | |
| self.test_client.get("/foo") | |
| assert "Some String" in log.getvalue() | |
| """ | |
| log = logging.getLogger(logger_name) | |
| log.setLevel(level) | |
| stream = StringIO() | |
| handler = logging.StreamHandler(stream) | |
| if formatter: | |
| handler.setFormatter(formatter) | |
| try: | |
| log.addHandler(handler) | |
| yield stream | |
| finally: | |
| stream.close() | |
| log.removeHandler(handler) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment