【问题标题】:Django Error Reporting - How to know which user triggered the error?Django 错误报告 - 如何知道哪个用户触发了错误?
【发布时间】:2011-07-13 12:30:19
【问题描述】:

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

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

提前非常感谢!

【问题讨论】:

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


    【解决方案1】:

    如果您不想使用 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_CLASSES 的引用。 IE。如果您将它放在项目根目录(您的 settings.py 所在的位置)的“中间件”文件中,您只需添加 middleware.ExceptionUserInfoMiddleware

    【讨论】:

    • 这看起来很简单。所以它所做的只是将这两个值添加到 Django 将包含在电子邮件中的内容中?那么django正常发送邮件了吗?
    • 我会把这个类放在什么文件中?然后我只是导入它并从 settings.py 中引用它?
    • 这在大多数情况下对我很有效。似乎引发了一些异常,并且没有调用此代码。例如,如果我弄乱了模板中的 URL,并且在模板呈现期间发生错误,则用户名不会包含在错误电子邮件中。我将中间件放在中间件列表的顶部。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 2015-07-20
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      相关资源
      最近更新 更多