Reusable Logging in Django Apps

I have 3 drafts sitting in my queue – 1 really long post and 2 short ones. I’ve been picking away at the long post on the shuttle rides, but in the meantime I’m gonna try to push out the two quick ones. This is one of the quick ones.

I was trying to figure out how to set up reusable logging in my apps and have it fairly decoupled from the overall project. Here’s what I came up with:

  1. Set up a logger object using these instructions in settings.py and store it in the LOGGER variable.
  2. Grab it inside apps using django.conf.settings like so:

from django.conf import settings
try:
    logging = settings.LOGGER
except AttributeError:
    import logging
Then just use logging.debug, logging.info etc. Thus, if a LOGGER is configured inside the project’s settings.py, we use that (django.conf.settings points to the settings.py for whatever project you’re working inside of, so you can move your app project to project no problem). Otherwise, we just use vanilla logging functions with the global logging configuration. Nice and sweet.

Suggestions on other ways to do this are, as always, welcome.

Example on django snippets: here.

Tags: , ,

2 Responses to “Reusable Logging in Django Apps”

  1. Nice tip.

    I tend to store all my logging related settings to loggers.py and loggers.cfg in the same place as settings.py. And from each module I do a “from myproject.loggers import mail_logger as logger” and so on.

    But don’t you think silently trapping exceptions like missing logger might be a recipe of future trouble. Least you should do when silently dropping errors is to log it, here you can’t even do that.

  2. mihasya says:

    The reason for storing it in the settings.py file is that you can then import from django.conf.settings, which is universal – you can move your app into another project and just define a LOGGER in that project’s settings.py. That is also the reason for the silent swap for the generic logger – if you have a LOGGER or generic logging configured, it’ll just work. If you haven’t configured logging at all, the log output will just go to stdout, so it’s not entirely silent. It’s not optimal, but my goal was to create a way for apps to be able to use a project-wide logger w/o making too big a fuss about it. If you really NEED the logs and have them configured, you will very quickly notice that the output isn’t coming, and will then have an easy way to fix it.

Leave a Reply