Tuesday, August 11, 2009

Enabling Bombproof Django Logging For Beginning a Project

"Hey, I installed Django and it doesn't work."
"Don't panic. Check the error logs."
"Logs? Django doesn't do logs."
"Python does. You have to add them into your project."
"Yes, but Django doesn't work. Now I am panicking."

And...cut. Beautifully acted all around. The point of the above is, there is a potential chicken-and-egg scenario brewing when you:
  1. Have a nonfunctioning Django app.
  2. Install logging to debug it.
  3. Can't run the application to test the logging...
  4. to run the application.
I poked around a bit in search of cut-n-paste logging scripts that get a project back into the light of day. I found a few, so thanks to lawfulsamurai and caktus for hearty illumination.

For brevity and to add a couple of caveats, I have combined what was published elsewhere into this quick how-to. Simply put, it will get you up and logging straight away. Just add it to your settings.py:
import logging
import logging.handlers

logger = logging.getLogger('project_logger')
logger.setLevel(logging.INFO)

# IMPORTANT, make sure python can write to the below log-file, or you will get an error
LOG_FILENAME = '/root/to/your/logging/dir/and/log-file'

LOG_MSG_FORMAT = '%(asctime)s %(levelname)s %(message)s'

handler = logging.FileHandler(LOG_FILENAME)

formatter = logging.Formatter(LOG_MSG_FORMAT)

handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info('testing logging')
There are some fine debugging options out there e.g. djangologging and the django debug toolbar. The advantage of the above is, it is simply a python module so you can't get more native than that.

Feel free to try whichever you find is best and to comment on this option.

No comments: