From 7a1c2c38632651d14e8549cf61ea0c1edabd9b4a Mon Sep 17 00:00:00 2001 From: Ramon Wenger Date: Thu, 5 Sep 2024 11:55:18 +0200 Subject: [PATCH] Add SentryGraphQLView from mySkillbox Improves GraphQL error message logging in Sentry --- server/config/urls.py | 4 ++-- server/vbv_lernwelt/api/views.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 server/vbv_lernwelt/api/views.py diff --git a/server/config/urls.py b/server/config/urls.py index 81ad63a1..0077db32 100644 --- a/server/config/urls.py +++ b/server/config/urls.py @@ -10,13 +10,13 @@ from django.urls.converters import IntConverter from django.views import defaults as default_views from django.views.decorators.csrf import csrf_exempt from django_ratelimit.exceptions import Ratelimited -from graphene_django.views import GraphQLView from wagtail import urls as wagtail_urls from wagtail.admin import urls as wagtailadmin_urls from wagtail.documents import urls as media_library_urls from vbv_lernwelt.api.directory import list_entities from vbv_lernwelt.api.user import get_profile, me_user_view, post_avatar +from vbv_lernwelt.api.views import SentryGraphQLView from vbv_lernwelt.assignment.views import request_assignment_completion_status from vbv_lernwelt.core.middleware.auth import django_view_authentication_exempt from vbv_lernwelt.core.schema import schema @@ -237,7 +237,7 @@ urlpatterns = [ ), path("server/graphql/", - csrf_exempt(GraphQLView.as_view(graphiql=True, schema=schema))), + csrf_exempt(SentryGraphQLView.as_view(graphiql=True, schema=schema))), # testing and debug path('server/raise_error/', user_passes_test(lambda u: u.is_superuser, login_url='/login/')( diff --git a/server/vbv_lernwelt/api/views.py b/server/vbv_lernwelt/api/views.py new file mode 100644 index 00000000..67de4d6d --- /dev/null +++ b/server/vbv_lernwelt/api/views.py @@ -0,0 +1,29 @@ +from django.http.request import HttpRequest +from graphene_django.views import GraphQLView +from graphql import get_operation_ast, parse +from sentry_sdk.api import start_transaction + + +# For sentry perfomance monitoring +# taken from https://jerrynsh.com/how-to-monitor-python-graphql-api-with-sentry/ +class SentryGraphQLView(GraphQLView): + def execute_graphql_request( + self, + request: HttpRequest, + data, + query, + variables, + operation_name, + show_graphiql, + ): + """ + adapted to use the new GraphQL 3.0 syntax, still need to get the operation type, + but the code to do this changed significantly, so the above link only explains + the 'what' and 'why', but no longer the 'how' + """ + document = parse(query) + operation_type = get_operation_ast(document, operation_name).operation + with start_transaction(op=str(operation_type), name=operation_name): + return super().execute_graphql_request( + request, data, query, variables, operation_name, show_graphiql + )