Для сбора статистики GraphQL запросов в Prometheus при использовании Graphene можно применить несколько подходов:
Использование prometheus_client
Сначала установите необходимые библиотеки:
pip install prometheus-client graphene
Создайте метрики для отслеживания:
from prometheus_client import Counter, Histogram, Gauge
import time
from graphene import ObjectType, Schema, Field, String
# Определяем метрики
graphql_requests_total = Counter(
'graphql_requests_total',
'Total number of GraphQL requests',
['operation_type', 'operation_name', 'status']
)
graphql_request_duration = Histogram(
'graphql_request_duration_seconds',
'GraphQL request duration',
['operation_type', 'operation_name']
)
graphql_field_resolver_duration = Histogram(
'graphql_field_resolver_duration_seconds',
'Duration of field resolver execution',
['field_name', 'parent_type']
)
graphql_errors_total = Counter(
'graphql_errors_total',
'Total number of GraphQL errors',
['operation_type', 'error_type']
)
Middleware для отслеживания запросов
Создайте middleware для перехвата и измерения запросов:
class PrometheusMiddleware:
def resolve(self, next, root, info, **args):
field_name = info.field_name
parent_type = info.parent_type.name
start_time = time.time()
try:
result = next(root, info, **args)
return result
finally:
duration = time.time() - start_time
graphql_field_resolver_duration.labels(
field_name=field_name,
parent_type=parent_type
).observe(duration)
Интеграция с Flask/Django
Для Flask:
from flask import Flask, request
from flask_graphql import GraphQLView
import json
app = Flask(__name__)
class InstrumentedGraphQLView(GraphQLView):
def dispatch_request(self):
start_time = time.time()
try:
# Парсим тело запроса для получения информации об операции
body = request.get_json()
query = body.get('query', '')
operation_name = body.get('operationName', 'unknown')
# Определяем тип операции
operation_type = 'unknown'
if query.strip().startswith('query'):
operation_type = 'query'
elif query.strip().startswith('mutation'):
operation_type = 'mutation'
elif query.strip().startswith('subscription'):
operation_type = 'subscription'
# Выполняем запрос
response = super().dispatch_request()
# Проверяем на ошибки
if response.status_code == 200:
response_data = json.loads(response.data)
if 'errors' in response_data:
status = 'error'
for error in response_data['errors']:
error_type = error.get('extensions', {}).get('code', 'unknown')
graphql_errors_total.labels(
operation_type=operation_type,
error_type=error_type
).inc()
else:
status = 'success'
else:
status = 'error'
# Записываем метрики
graphql_requests_total.labels(
operation_type=operation_type,
operation_name=operation_name,
status=status
).inc()
duration = time.time() - start_time
graphql_request_duration.labels(
operation_type=operation_type,
operation_name=operation_name
).observe(duration)
return response
except Exception as e:
graphql_requests_total.labels(
operation_type='unknown',
operation_name='unknown',
status='error'
).inc()
raise
# Регистрируем view
app.add_url_rule(
'/graphql',
view_func=InstrumentedGraphQLView.as_view(
'graphql',
schema=schema,
graphiql=True,
middleware=[PrometheusMiddleware()]
)
)
Кастомный execution context
Можно также создать кастомный execution context для более детального отслеживания:
from graphql.execution import ExecutionContext
from graphql.execution.execute import execute_sync
class InstrumentedExecutionContext(ExecutionContext):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.field_timings = {}
def execute_field(self, parent_type, source, field_nodes, path):
field_name = field_nodes[0].name.value
start_time = time.time()
try:
result = super().execute_field(parent_type, source, field_nodes, path)
return result
finally:
duration = time.time() - start_time
graphql_field_resolver_duration.labels(
field_name=field_name,
parent_type=parent_type.name
).observe(duration)
Экспорт метрик
Добавьте endpoint для экспорта метрик:
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST
@app.route('/metrics')
def metrics():
return generate_latest(), 200, {'Content-Type': CONTENT_TYPE_LATEST}
Дополнительные метрики
Можно также отслеживать:
# Сложность запросов
graphql_query_complexity = Histogram(
'graphql_query_complexity',
'Complexity score of GraphQL queries',
['operation_type']
)
# Глубина запросов
graphql_query_depth = Histogram(
'graphql_query_depth',
'Depth of GraphQL queries',
['operation_type']
)
# Количество запрашиваемых полей
graphql_fields_requested = Histogram(
'graphql_fields_requested',
'Number of fields requested in query',
['operation_type']
)
Для вычисления этих метрик можно использовать библиотеку graphql-query-complexity или написать собственный анализатор AST запроса.
Эта система позволит вам отслеживать производительность GraphQL API, выявлять медленные резолверы и проблемные запросы через Prometheus и визуализировать их в Grafana.