Skip to content

Commit

Permalink
capture user/org tags in sentry
Browse files Browse the repository at this point in the history
  • Loading branch information
sravfeyn committed Dec 6, 2024
1 parent 41b7557 commit 30b5ab6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
28 changes: 28 additions & 0 deletions commcare_connect/utils/middleware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import MiddlewareNotUsed
from django.http import HttpResponseRedirect
from django.utils.safestring import mark_safe
from rest_framework.settings import api_settings
Expand Down Expand Up @@ -40,3 +42,29 @@ def __call__(self, request):
def process_view(self, request, view_func, view_args, view_kwargs):
if hasattr(view_func, "cls") and view_func.cls.versioning_class is not None:
request.include_version_headers = True


class SentryContextMiddleware:
"""Add details to Sentry context.
Should be placed after '"commcare_connect.users.middleware.OrganizationMiddleware",'
"""

def __init__(self, get_response):
self.get_response = get_response
try:
from sentry_sdk import Scope # noqa: F401
except ImportError:
raise MiddlewareNotUsed

if not getattr(settings, "SENTRY_DSN", None):
raise MiddlewareNotUsed

def process_view(self, request, view_func, view_args, view_kwargs):
from sentry_sdk import configure_scope

with configure_scope() as scope:
if getattr(request, "user", None):
scope.set_user("username", request.user.username)

if getattr(request, "org", None):
scope.set_tag("org", request.org)
1 change: 1 addition & 0 deletions config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"commcare_connect.utils.middleware.CustomErrorHandlingMiddleware",
"commcare_connect.utils.middleware.CurrentVersionMiddleware",
"commcare_connect.utils.middleware.SentryContextMiddleware",
]

# STATIC
Expand Down

0 comments on commit 30b5ab6

Please sign in to comment.