Basic Python Logging in Django 1.2: Debugging Made Simple

python-logWhen I was deploying my new social shopping site Wantbox a couple of month ago, I discovered that I couldn’t use the Django print command in my live Dreamhost (Passenger WSGI) environment like this:

   print "Hello world!"

As a new site, I was still debugging a few persistent nits and really needed to print out messages when certain areas of the code were accessed. A few sites recommended that I try the Django debug toolbar, but I was having trouble getting that to work reliably in my Dreamhost setup.

I searched around a bit more and after consuming many web pages, finally discovered a dead simple solution using the built-in Python logging module.

Python Logging in Django, Step-by-Step:

  1. Open your “settings.py” file and add this code to the bottom:
    # setup logger
    import logging
    PROJECT_DIR = os.path.dirname(__file__)
    PARENT_DIR = os.path.dirname(PROJECT_DIR)
    logging.basicConfig(level=logging.DEBUG,
         format='%(asctime)s %(levelname)s %(message)s',
         filename=os.path.join(PARENT_DIR, 'django.log'),
         filemode='a+')</pre>
  2. Create a file called “django.log” at the same level as your project, my setup looks like:
    .
    ..
    .htaccess
    django.log
    passenger_wsgi.py
    passenger_wsgi.pyc
    public
    tmp
    wantbox (my django project)
  3. In the view where you need to “print” add the following:
    import logging
    logging.debug("hello world!")
    logging.info("this is some interesting info!")
    logging.error("this is an error!")

Now you can do…

tail -f django.log

…and see every logging message that you (and your third-party apps) write. So easy, yet still took this Django rookie a good day of Google searching to figure out. Here’s hoping I’ve saved at least one of you from my fate.

Helpful Resources:

UPDATE!

Check out the suggestions from the Django pros in the comments for some nice improvements to this simple logging example!