Django Syslog Middleware
Hi Folks,
for some time, Alex and I have been working on a simple Book Rating system for school, which, of course, was developed using Django. It sits on a PostgeSQL database and authenticates users against an LDAP which the school runs – pretty neat. However, for reasons of time and safety we do not fancy setting up a webserver to get mails every time an error occurs (still quite frequently according to the users). What to do? Apache Error logs are not very meaningful, since all they say is „Provide a 404 Template“:.. aint gonna do that! The shortest way around was simply writing up a Middleware, which, upon error, would write request and exception to the syslog – sorry Windows users, YOU can not use it. Aside I figured it’d be neat to also have a full fledged output file right in app, even though Alex didn’t like the idea too much, granted, the syslog thing IS cooler. So I ended up implementing that funky solution which nobody ever seemed to have thought of (????). Here’s the code:
from syslog import * import time
class SyslogOutput:
def process_exception(self, request, exception):
# Compile the string for the exception in the format: "Variable: Value" so as to make it readable
request_string = ""
filename='/var/www/django/log/%s_error.csv'%(time.strftime('%y-%m-%d-%H-%M-%s'))
txt = file(filename, 'w')
for item in dir(request):
value = getattr(request, item)
request_string += "%s: %s\n"%(item, value)
request_string += "\n\Exception: %s"%(exception)
syslog (LOG_DEBUG, request_string)
txt.writelines("Exception: %s"%(request_string))
txt.close()
return None
If you find it helpful or have any contributions to improve the behavior, please feel free to comment! Hope this helps some folks getting the logs they want.