Using logging.X in Django to log information in a file

I didn't know how to use the logging infrastructure from Django so I thought I'd write a quick post about how to use it.

I wrote this article for logging in Django 1.3. You can find the official documentation at https://docs.djangoproject.com/en/1.3/topics/logging/ and http://docs.python.org/library/logging.html for the Python logging module used with Django

Configuration

The default Django configuration is sane already, but doesn't save anything to file, nor doesn't give any example on how to do it.

Your first need to add this handler to the LOGGING configuration.

'file': {
    'level': 'DEBUG',
    'class': 'logging.FileHandler',
    'filename': '/tmp/project_log.log'
},

Configure it to handle "core.views" logger.

'loggers': {
    'core.views': { # the logger name
        'handlers': ['file'],
        'level': 'DEBUG',
        'propagate': True,
    },
}

The full configuration could look like this.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/tmp/project_log.log'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'core.views': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

Pro tip: you can replace the logger name by an empty string '' to catch all the logging calls from everywhere (source : http://stackoverflow.com/a/5439502/97976). But beware! It is NOISY.

Usage

Finally, in the module where you want to log information usage the usage is straightforward and already described in the Django documentation.

import logging
logger = logging.getLogger(__name__)

# somewhere in the code
logger.info("Just loggin' you know")

3. Conclusion

What is missing in the official documentation is some discussion about useful handlers such as the FileHandler.

Good news is that such documentation exists at http://docs.python.org/howto/logging.html#useful-handlers so if you (or me) have time to add a couple of lines about it to the official Django documentation please do it!