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:
           logged_in_info = ''
           if request.user and request.user.is_authenticated():
               logged_in_info = "%s" % request.user
                   logged_in_info += ' %s' %
               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
           # 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():


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.


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


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.


Stay with this guys, you're helping a lot of pelope.

Your email will never ever be published.

Related posts