forked from mtusi2026/mtusi2026lab6
feat: ЛР6 - наблюдаемость OpenTelemetry, Grafana и исследование цены наблюдаемости
This commit is contained in:
+75
-35
@@ -1,41 +1,62 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from opentelemetry.trace import SpanKind
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
from app.config import INSTANCE_ID
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
stream=sys.stdout,
|
||||
from app.telemetry import (
|
||||
get_tracer,
|
||||
record_http_request,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("app.access")
|
||||
|
||||
ROUTE_CHATS_MESSAGES = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+/messages$")
|
||||
ROUTE_CHATS_ATTACHMENTS = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+/attachments$")
|
||||
ROUTE_CHATS_ID = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+$")
|
||||
ROUTE_ATTACHMENTS_CONTENT = re.compile(r"^/api/v1/attachments/[0-9a-fA-F-]+/content$")
|
||||
ROUTE_ATTACHMENTS_ID = re.compile(r"^/api/v1/attachments/[0-9a-fA-F-]+$")
|
||||
|
||||
|
||||
def get_route_template(path: str) -> str:
|
||||
if ROUTE_CHATS_MESSAGES.match(path):
|
||||
return "/api/v1/chats/{chat_id}/messages"
|
||||
if ROUTE_CHATS_ATTACHMENTS.match(path):
|
||||
return "/api/v1/chats/{chat_id}/attachments"
|
||||
if ROUTE_CHATS_ID.match(path):
|
||||
return "/api/v1/chats/{chat_id}"
|
||||
if ROUTE_ATTACHMENTS_CONTENT.match(path):
|
||||
return "/api/v1/attachments/{attachment_id}/content"
|
||||
if ROUTE_ATTACHMENTS_ID.match(path):
|
||||
return "/api/v1/attachments/{attachment_id}"
|
||||
return path
|
||||
|
||||
|
||||
class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(
|
||||
self, request: Request, call_next: RequestResponseEndpoint
|
||||
) -> Response:
|
||||
# Получаем X-Request-Id или генерируем новый
|
||||
request_id = request.headers.get("X-Request-Id")
|
||||
if not request_id or not request_id.strip():
|
||||
request_id = str(uuid.uuid4())
|
||||
|
||||
request.state.request_id = request_id
|
||||
start_time = time.monotonic()
|
||||
path = request.url.path
|
||||
route_template = get_route_template(path)
|
||||
|
||||
if request.method in ("POST", "PUT", "PATCH") and request.url.path != "/api/v1/auth/sessions":
|
||||
if request.method in ("POST", "PUT", "PATCH") and path != "/api/v1/auth/sessions":
|
||||
is_attachment_upload = (
|
||||
request.method == "POST"
|
||||
and "/attachments" in request.url.path
|
||||
and request.url.path.startswith("/api/v1/chats/")
|
||||
and "/attachments" in path
|
||||
and path.startswith("/api/v1/chats/")
|
||||
)
|
||||
ct = request.headers.get("content-type")
|
||||
ct_clean = ct.split(";")[0].strip().lower() if ct else ""
|
||||
@@ -62,32 +83,51 @@ class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware):
|
||||
request_id,
|
||||
)
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
# Исключение перехватится exception_handler
|
||||
duration_ms = (time.monotonic() - start_time) * 1000
|
||||
logger.error(
|
||||
"%s %s -> 500 error | duration=%.2fms | request_id=%s",
|
||||
tracer = get_tracer()
|
||||
with tracer.start_as_current_span(
|
||||
f"{request.method} {route_template}",
|
||||
kind=SpanKind.SERVER,
|
||||
) as span:
|
||||
span.set_attribute("http.method", request.method)
|
||||
span.set_attribute("http.route", route_template)
|
||||
span.set_attribute("http.target", path)
|
||||
span.set_attribute("request.id", request_id)
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
duration_sec = time.monotonic() - start_time
|
||||
span.set_attribute("http.status_code", 500)
|
||||
span.record_exception(Exception("Unhandled server error"))
|
||||
record_http_request(request.method, route_template, "500", duration_sec)
|
||||
logger.error(
|
||||
"%s %s -> 500 error | duration=%.2fms | request_id=%s",
|
||||
request.method,
|
||||
path,
|
||||
duration_sec * 1000,
|
||||
request_id,
|
||||
)
|
||||
raise
|
||||
|
||||
duration_sec = time.monotonic() - start_time
|
||||
span.set_attribute("http.status_code", response.status_code)
|
||||
|
||||
record_http_request(request.method, route_template, str(response.status_code), duration_sec)
|
||||
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
|
||||
ctx = span.get_span_context()
|
||||
if ctx.is_valid:
|
||||
response.headers["X-Trace-Id"] = format(ctx.trace_id, "032x")
|
||||
|
||||
logger.info(
|
||||
"%s %s -> %d | duration=%.2fms | request_id=%s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
duration_ms,
|
||||
path,
|
||||
response.status_code,
|
||||
duration_sec * 1000,
|
||||
request_id,
|
||||
)
|
||||
raise
|
||||
|
||||
duration_ms = (time.monotonic() - start_time) * 1000
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
|
||||
# лог без логирования тела запросов и текстов сообщений
|
||||
logger.info(
|
||||
"%s %s -> %d | duration=%.2fms | request_id=%s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
response.status_code,
|
||||
duration_ms,
|
||||
request_id,
|
||||
)
|
||||
|
||||
return response
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user