Created
January 8, 2014 18:05
-
-
Save JeromeParadis/8321365 to your computer and use it in GitHub Desktop.
How to generate a logger that logs to a string.
This file contains 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 | |
def get_string_logger(logger_name, level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", debug_db=False): | |
""" | |
Gets you what you need to log to a string. Returns a pair of StringIO, logger variables. | |
>>> output, logger = get_string_logger('my_app_logger', level=logging.DEBUG) | |
>>> call_stuff_to_debug_with_logger(logger=logger) | |
>>> print output.getvalue() | |
""" | |
import StringIO | |
if not debug_db: | |
from django.db.backends import BaseDatabaseWrapper | |
from django.db.backends.util import CursorWrapper | |
# Disable database debug: http://stackoverflow.com/questions/7768027/turn-off-sql-logging-while-keeping-settings-debug | |
BaseDatabaseWrapper.make_debug_cursor = lambda self, cursor: CursorWrapper(cursor, self) | |
logger = logging.getLogger(logger_name) | |
logger.setLevel(logging.DEBUG) | |
formatter = logging.Formatter(format) | |
output = StringIO.StringIO() | |
string_handler = logging.StreamHandler(output) | |
string_handler.setFormatter(formatter) | |
string_handler.setLevel(level) | |
logger.addHandler(string_handler) | |
return output, logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment