Skip to content

Instantly share code, notes, and snippets.

Created January 8, 2014 18:05
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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:
BaseDatabaseWrapper.make_debug_cursor = lambda self, cursor: CursorWrapper(cursor, self)
logger = logging.getLogger(logger_name)
formatter = logging.Formatter(format)
output = StringIO.StringIO()
string_handler = logging.StreamHandler(output)
return output, logger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment