15 April 2010 5 comments Django
In lack of a fancier solution here's how I solved a problem of knowing who was logged in when an error occurred. I'm building a Intranet like system for a close group of people and if an error occurs I get an email that reminds me to add more tests. So I fix the bugs and upgrade the server. But I often want to know what poor sucker was logged in at the time the exception happened so that I can email them and say something like "Hi! I noticed your stumbled across a bug. My bad. Just wanted to let you know I've fixed that now"
So to do this I installed a silly little piece of middleware:
from django.conf import settings class ExceptionExtraMiddleware(object): def process_exception(self, request, exception): if settings.DEBUG: return try: logged_in_info = '' if request.user and request.user.is_authenticated(): logged_in_info = "%s" % request.user if request.user.email: logged_in_info += ' %s' % request.user.email if request.user.first_name or request.user.last_name: logged_in_info += ' (%s %s)' % \ (request.user.first_name, request.user.last_name) if logged_in_info: request.META['ERROR-X-LOGGED-IN'] = logged_in_info except: # don't make matters worse in these sensitive times logging.debug("Unable to debug who was logged in", exc_info=True)
This means that when I get an email with the traceback and snapshot of the request object I get this included:
... 'ERROR-X-LOGGED-IN': u'anita (Anita Test)', ...
The code above had a bug in it. Doing an if on
request.user will return true even if there is no logged in user. The safest thing is to change it to:
if request.user and request.user.is_authenticated():