Django Logging Setup

Post 1.3, Django has some nice integration with the python logging module. It can dictConf to specify the formatters, handlers, etc. This is all pretty well documented here.

What wasn’t immediately obvious (to me anyway) was that you can use any of the handlers in django logging and pass the __init__ params to them in this config. So for example if you want to have a log which rotates everyday and keep a week of these files, then you can simply define:

'handlers': {
        # Other handlers here
        'rotating_file':
        {
            'level' : 'DEBUG',
            'formatter' : 'verbose', # from the django doc example
            'class' : 'logging.handlers.TimedRotatingFileHandler',
            'filename' :   MY_LOG_FILENAME, # full path works
            'when' : 'midnight',
            'interval' : 1,
            'backupCount' : 7,
        },


and then use this handler for a logger:

'loggers': {
         # other loggers
         'my_logger': {
            'handlers': ['rotating_file'],
            'level': 'DEBUG',
        }
    }

You can use this logger in your app by grabbing the logger:

logger = logging.getLogger('my_logger')

And log away!

logger.warn("Here be Dragons!")

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>