forked from mtusi2026/mtusi2026lab3
feat: перенос структуры приложения из второй лабы
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
logger = logging.getLogger("app.access")
|
||||
|
||||
|
||||
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()
|
||||
|
||||
if request.method in ("POST", "PUT", "PATCH") and request.url.path != "/api/v1/auth/sessions":
|
||||
ct = request.headers.get("content-type")
|
||||
if ct:
|
||||
ct_clean = ct.split(";")[0].strip().lower()
|
||||
if ct_clean != "application/json":
|
||||
from fastapi import status
|
||||
from app.errors import make_error_response
|
||||
from app.schemas import ErrorCode
|
||||
return make_error_response(
|
||||
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
|
||||
ErrorCode.UNSUPPORTED_MEDIA_TYPE,
|
||||
f"Неподдерживаемый тип содержимого '{ct}'. Ожидается application/json",
|
||||
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",
|
||||
request.method,
|
||||
request.url.path,
|
||||
duration_ms,
|
||||
request_id,
|
||||
)
|
||||
raise
|
||||
|
||||
duration_ms = (time.monotonic() - start_time) * 1000
|
||||
response.headers["X-Request-Id"] = request_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
|
||||
Reference in New Issue
Block a user