From 30b5ab6f1cdd39a940d4f026af445f9e7053c2d9 Mon Sep 17 00:00:00 2001 From: Sravan Reddy Date: Fri, 6 Dec 2024 15:24:43 +0530 Subject: [PATCH] capture user/org tags in sentry --- commcare_connect/utils/middleware.py | 28 ++++++++++++++++++++++++++++ config/settings/base.py | 1 + 2 files changed, 29 insertions(+) diff --git a/commcare_connect/utils/middleware.py b/commcare_connect/utils/middleware.py index efb5d188..f54f5661 100644 --- a/commcare_connect/utils/middleware.py +++ b/commcare_connect/utils/middleware.py @@ -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 @@ -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) diff --git a/config/settings/base.py b/config/settings/base.py index 227224ef..90b0ee65 100644 --- a/config/settings/base.py +++ b/config/settings/base.py @@ -125,6 +125,7 @@ "django.middleware.clickjacking.XFrameOptionsMiddleware", "commcare_connect.utils.middleware.CustomErrorHandlingMiddleware", "commcare_connect.utils.middleware.CurrentVersionMiddleware", + "commcare_connect.utils.middleware.SentryContextMiddleware", ] # STATIC