Django – Logging in Views
December 17, 2009
I have searched as many places I could looking for an advisable way of logging within views in Django. I found a lot of advice, apps, code, etc. But I did not find anything easy, beautiful, or even understandable for someone with my limited knowledge. So I did what anyone in need would do: create an app of my own which can be used within views.py for any and all apps and projects.
The main idea was to use Python’s
logging module but abstract it enough so that any developer can configure it easily. The code has been structured thus: a directory called django-logbook (or even djangologbook) which needs to be placed on Python’s path, preferably in the Django project folder. This directory contains at least three files, with more files included depending on the number of apps using Django-LogBook (my name for the app). These three files are: __init__.py, django-logbook.py, and sample.py. __init__.py is empty and is present so that the logbook directory can be considered a package or module by Python.
django-logbook.py contains the heart of the app. It contains a class calls LogBook which can be instantiated by any app. To make things easier in terms of management, I have added a sample.py which does the instantiation. The idea is to create separate log files for separate apps. Therefore, each app has its own appname.py in the logbook directory. Just copy sample.py and rename it as appname.py. Then in your views.py import the appname.py.
You don’t even have to import the whole appname.py in views.py. All you have to do is import as below:
from PROJECTNAME.logbook.APPNAME import djangologbookentry
Then within your views, you can log as below:
django-logbookentry.info('My info message')
django-logbookentry.error('2009-12-16 23:59', 'OMG an error')
In your appname.py in django-logbook directory, you need to provide three things: unique identification of logger for the app, name of the log file, and level of log messages. By default it is setup to log up to 5 files, each file 200,000 bytes in size.
For detailed configuration, you can view and modify the LogBook class.