Who was logged in during a Django exception

15 April 2010   5 comments   Django

Powered by Fusion×

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)',
...

UPDATE

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():

Comments

Eric Walstad
Looks good, Peter. Thanks for sharing.
David Ziegler
The traceback include the session id. What I do is lookup the session, which will contain the user's id if the person was logged in.

e.g.

session = Session.objects.get("7ac7fa8d7cf56a826c94a559434a9c7c")
data = session.get_decoded()
user = User.objects.get(data['_auth_user_id'])
karthikr
Hello David,

Your solution seems feasible, however if the user has logged out, it becomes cumbersome to find the user whose login caused the error
Peter Bengtsson
But if they're logged out you can't know who caused the error and that's just tough.
Bobbi
Stay with this guys, you're helping a lot of pelope.
Thank you for posting a comment

Your email will never ever be published


Related posts

Previous:
fcgi vs. gunicorn vs. uWSGI 09 April 2010
Next:
UPPER vs. ILIKE 19 April 2010
Related:
Chainable catches in a JavaScript promise 05 November 2015
Careful with your assertRaises() and inheritance of exceptions 10 April 2013
pg_class to check if table exists 20 April 2005