9

Is there a way I can customize Django error reporting so when it emails me it lets me know which user triggered the error?

I'm in Django 1.2 if it matters.

Much Thanks in advance!

Greg
  • 45,306
  • 89
  • 231
  • 297

2 Answers2

14

If you don't want to use sentry you can use this simple middleware to attache the user-infos to the error mail:

# source: https://gist.github.com/646372
class ExceptionUserInfoMiddleware(object):
    """
    Adds user details to request context on receiving an exception, so that they show up in the error emails.

    Add to settings.MIDDLEWARE_CLASSES and keep it outermost(i.e. on top if possible). This allows
    it to catch exceptions in other middlewares as well.
    """

    def process_exception(self, request, exception):
        """
        Process the exception.

        :Parameters:
           - `request`: request that caused the exception
           - `exception`: actual exception being raised
        """

        try:
            if request.user.is_authenticated():
                request.META['USERNAME'] = str(request.user.username)
                request.META['USER_EMAIL'] = str(request.user.email)
        except:
            pass

You can simply put this class in a *.py file anywhere below your Django project and add a reference to MIDDLEWARE_CLASSES. I.e. if you put it in a file "middleware" in the project root (where your settings.py is) , you simply add middleware.ExceptionUserInfoMiddleware.

Martin Thurau
  • 7,564
  • 7
  • 43
  • 80
  • This looks simple. So all it's doing is adding these two values to the stuff Django is going to include in the email anyway? Then Django sends the email normally? – Greg Jul 13 '11 at 17:05
  • What file would I put this class in? And then I just import it and reference it from settings.py? – Greg Jul 13 '11 at 17:06
  • This works well for me in most cases. It seems some exceptions are raised and this code isn't called. For example, if I mess up a URL in a template and the error happens during the template rendering, the username doesn't get included on the error email. I include the middleware at the top of my middleware list. – cjd82187 Sep 09 '14 at 13:22
2

I highly recommend http://readthedocs.org/docs/sentry/en/latest/index.html for the job.

iElectric
  • 5,633
  • 1
  • 29
  • 31