Django错误报告 - 如何知道哪个用户触发了错误?

时间:2011-07-13 12:30:19

标签: python django django-middleware django-email django-errors

有没有办法可以自定义Django错误报告,所以当它通过电子邮件发送给我时,它会让我知道哪个用户触发了错误?

如果重要的话,我在Django 1.2中。

非常感谢提前!

2 个答案:

答案 0 :(得分:14)

如果您不想使用哨兵,您可以使用这个简单的中间件将用户信息附加到错误邮件:

# 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

您可以简单地将此类放在Django项目下方的* .py文件中,并添加对MIDDLEWARE_CLASSES的引用。即如果你把它放在项目根目录中的“中间件”文件中(你的settings.py就是),你只需添加middleware.ExceptionUserInfoMiddleware

答案 1 :(得分:2)

我强烈推荐http://readthedocs.org/docs/sentry/en/latest/index.html来完成这项工作。