Django 如何在发生错误时将用户信息添加到 Sentry 的报告中?

Django How to add user info to Sentry's report when an error happened?

我使用的是 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({...})

谁能给我一些建议? :)

如评论中所述,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/

如此处所述: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:个人身份信息

P.S。不要忘记在 installed_apps.

中包含 django.contrib.auth