Search code examples
djangodjango-rest-frameworksentry

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


I use the django-restful framework and I want to add user info to Sentry's report when an error happened in the ModelViewSet.

I find this doc of Sentry: https://docs.sentry.io/enriching-error-data/context/?_ga=1.219964441.1220115692.1472094716%3F_ga&platform=python#capturing-the-user

It gives some code as follows:

from sentry_sdk import configure_scope

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

But I can not figure out how to properly use it. I think there exists a better way than the following:

@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({...})

Can anyone give me some suggestions? :)


Solution

  • As mentioned in the comments, the Django integration will attach this particular data automatically.

    As for the question on how to generally add data in a Django app, you are basically looking for something to run before each view. A Django middleware suits this:

    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/