【问题标题】:Django How to add user info to Sentry's report when an error happened?Django 发生错误时如何将用户信息添加到 Sentry 的报告中?
【发布时间】:2019-09-08 17:46:10
【问题描述】:

我使用 django-restful 框架,当 ModelViewSet 发生错误时,我想将用户信息添加到 Sentry 的报告中。

我找到了 Sentry 的这个文档: https://docs.sentry.io/enriching-error-data/context/?_ga=1.219964441.1220115692.1472094716%3F_ga&platform=python#capturing-the-user

它给出了一些代码如下:

from sentry_sdk import configure_scope

with configure_scope() as scope:
    scope.user = {"email": "john.doe@example.com"}

但我不知道如何正确使用它。我认为存在比以下更好的方法:

@list_route()
def fun_xxx(self, request, *args, **kwargs):
  user = request.user
  with configure_scope() as scope:
     scope.user = {"id": user.id,......}

  ...some code may cause an error...

  return Response({...})

谁能给我一些建议? :)

【问题讨论】:

  • 如果您使用的是 Sentry Django client,则会自动包含此数据。

标签: django django-rest-framework sentry


【解决方案1】:

如 cmets 中所述,Django 集成将自动附加此特定数据。

关于如何在 Django 应用程序中添加数据的问题,您基本上是在寻找在每个视图之前运行的东西。一个 Django 中间件适合这个:

def sentry_middleware(get_response):

    def middleware(request):
        with configure_scope() as scope:
            ...

        response = get_response(request)
        return response

    return middleware

https://docs.djangoproject.com/en/2.2/topics/http/middleware/

【讨论】:

    【解决方案2】:

    这里提到:https://docs.sentry.io/platforms/python/guides/django/#configure

    设置:

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
    
        send_default_pii=True,
    

    在 Django 中配置哨兵时。

    PII:个人身份信息

    附:不要忘记在您的 installed_apps 中包含 django.contrib.auth。

    【讨论】:

      猜你喜欢
      • 2020-04-03
      • 2020-06-24
      • 1970-01-01
      • 2015-05-19
      • 2021-02-17
      • 2018-04-30
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多