Django Error Reporting - How to know which user triggered the error?

…衆ロ難τιáo~ 提交于 2019-12-04 03:02:04

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!