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

9 投票
2 回答
1453 浏览
提问于 2025-04-16 21:25

有没有办法让我自定义Django的错误报告,这样当它给我发邮件的时候,可以告诉我是哪位用户引发了这个错误?

我现在用的是Django 1.2,如果这有关系的话。

非常感谢!

2 个回答

2

我强烈推荐你去看看这个网站:http://readthedocs.org/docs/sentry/en/latest/index.html,它对这个工作非常有帮助。

14

如果你不想使用sentry这个工具,可以用这个简单的中间件来把用户信息附加到错误邮件里:

# 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”的文件里(也就是settings.py所在的地方),你只需添加

撰写回答