Create a gist now

Instantly share code, notes, and snippets.

How to generate a logger that logs to a string.
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