Django Logging

Logging in Django doesn't have to be painful. Here is a quick setup I use.

settings.py

import logging
import os

ROOT_PATH = os.path.dirname(file) LOG_DIR = os.path.join(ROOT_PATH, "logs") LOG_FILE = os.path.join(LOG_DIR, "myapp.log")

log = logging.getLogger("myapp") log.level = logging.DEBUG formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

# log to console ch = logging.StreamHandler() ch.setFormatter(formatter) log.addHandler(ch)

# log to file fh = logging.FileHandler(LOG_FILE) fh.setFormatter(formatter) log.addHandler(fh)

models.py

import logging
log = logging.getLogger("myapp.feeds.model")

#log some stuff log.info("Something happened") log.debug("Lots of boring boring detail") log.error("The sky is falling...")

#switch namespaces log = logging.getLogger("myapp.users") log.info("User %s deleted" % "username")

myapp.log file

20100324... - myapp.feeds.model - INFO - Something Happened
20100324... - myapp.feeds.model - DEBUG - Lots of boring boring detail
20100324... - myapp.feeds.model - ERROR - The sky is falling...
20100324... - myapp.users - INFO - User username deleted