исправления dashboard

This commit is contained in:
2026-12-04 04:59:46 +03:00
parent 3ba5126b78
commit 54ccb8efc6
4 changed files with 45 additions and 10 deletions
+36 -7
View File
@@ -2,6 +2,7 @@ import os
import uuid import uuid
import logging import logging
import asyncio import asyncio
import time
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from app.telemetry import setup_telemetry from app.telemetry import setup_telemetry
@@ -12,7 +13,7 @@ from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import HTTPException as StarletteHTTPException
from opentelemetry import trace, propagate from opentelemetry import trace, propagate, metrics
from opentelemetry.trace import SpanKind, StatusCode from opentelemetry.trace import SpanKind, StatusCode
from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor
from opentelemetry.instrumentation.aio_pika import AioPikaInstrumentor from opentelemetry.instrumentation.aio_pika import AioPikaInstrumentor
@@ -24,6 +25,13 @@ logger = logging.getLogger(__name__)
tracer = trace.get_tracer("messenger-api") tracer = trace.get_tracer("messenger-api")
INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4())[:8]) INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4())[:8])
# HTTP-метрики
_http_meter = metrics.get_meter("messenger.http")
_http_duration = _http_meter.create_histogram(
"http.server.duration", unit="ms",
description="Measures the duration of inbound HTTP requests",
)
class OtelASGIMiddleware: class OtelASGIMiddleware:
def __init__(self, app): def __init__(self, app):
@@ -37,6 +45,9 @@ class OtelASGIMiddleware:
path = scope.get("path", "?") path = scope.get("path", "?")
carrier = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])} carrier = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])}
parent_ctx = propagate.extract(carrier) parent_ctx = propagate.extract(carrier)
started = time.perf_counter()
status_holder = {"code": 0}
with tracer.start_as_current_span( with tracer.start_as_current_span(
name=f"{method} {path}", context=parent_ctx, kind=SpanKind.SERVER, name=f"{method} {path}", context=parent_ctx, kind=SpanKind.SERVER,
attributes={"http.method": method, "http.target": path}, attributes={"http.method": method, "http.target": path},
@@ -50,15 +61,27 @@ class OtelASGIMiddleware:
async def send_wrapper(message): async def send_wrapper(message):
if message["type"] == "http.response.start": if message["type"] == "http.response.start":
span.set_attribute("http.status_code", message.get("status", 0)) status_holder["code"] = message.get("status", 0)
if message.get("status", 0) >= 500: span.set_attribute("http.status_code", status_holder["code"])
if status_holder["code"] >= 500:
span.set_status(StatusCode.ERROR) span.set_status(StatusCode.ERROR)
h = list(message.get("headers", [])) h = list(message.get("headers", []))
h.append((b"x-request-id", scope["state"]["request_id"].encode())) h.append((b"x-request-id", scope["state"]["request_id"].encode()))
h.append((b"x-instance-id", INSTANCE_ID.encode())) h.append((b"x-instance-id", INSTANCE_ID.encode()))
message["headers"] = h message["headers"] = h
await send(message) await send(message)
try:
await self.app(scope, receive, send_wrapper) await self.app(scope, receive, send_wrapper)
finally:
dur_ms = (time.perf_counter() - started) * 1000.0
attrs = {
"http.method": method,
"http.target": path,
"http.status_code": status_holder["code"],
}
print(f"!!! METRIC: {method} {path} {dur_ms:.1f}ms", flush=True)
_http_duration.record(dur_ms, attrs)
@asynccontextmanager @asynccontextmanager
@@ -67,6 +90,7 @@ async def lifespan(app: FastAPI):
queue_task = asyncio.create_task(collect_queue_metrics()) queue_task = asyncio.create_task(collect_queue_metrics())
yield yield
tracer_provider.force_flush(timeout_millis=5000) tracer_provider.force_flush(timeout_millis=5000)
meter_provider.force_flush(timeout_millis=5000)
task.cancel() task.cancel()
queue_task.cancel() queue_task.cancel()
@@ -85,16 +109,21 @@ async def http_exception_handler(request: Request, exc: StarletteHTTPException):
detail = exc.detail detail = exc.detail
code = detail.get("code", "internal_error") if isinstance(detail, dict) else "internal_error" code = detail.get("code", "internal_error") if isinstance(detail, dict) else "internal_error"
message = detail.get("message", str(detail)) if isinstance(detail, dict) else str(detail) message = detail.get("message", str(detail)) if isinstance(detail, dict) else str(detail)
return JSONResponse(status_code=exc.status_code, return JSONResponse(
status_code=exc.status_code,
content={"error": {"code": code, "message": message, content={"error": {"code": code, "message": message,
"request_id": getattr(request.state, "request_id", "")}}, headers=exc.headers) "request_id": getattr(request.state, "request_id", "")}},
headers=exc.headers,
)
@app.exception_handler(RequestValidationError) @app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError): async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(status_code=400, return JSONResponse(
status_code=400,
content={"error": {"code": "invalid_request", "message": "Validation error", content={"error": {"code": "invalid_request", "message": "Validation error",
"request_id": getattr(request.state, "request_id", "")}}, "request_id": getattr(request.state, "request_id", "")}},
headers={"X-Request-Id": getattr(request.state, "request_id", ""), "X-Instance-Id": INSTANCE_ID}) headers={"X-Request-Id": getattr(request.state, "request_id", ""), "X-Instance-Id": INSTANCE_ID},
)
@app.get("/health/live") @app.get("/health/live")
async def health_live(): async def health_live():
+2
View File
@@ -88,6 +88,8 @@ services:
otel-collector: otel-collector:
image: otel/opentelemetry-collector-contrib:0.163.2 image: otel/opentelemetry-collector-contrib:0.163.2
ports:
- "9464:9464"
command: ["--config=/etc/otelcol-contrib/collector.yaml"] command: ["--config=/etc/otelcol-contrib/collector.yaml"]
volumes: volumes:
- ./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro - ./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro
+1 -1
View File
@@ -27,7 +27,7 @@ exporters:
otlp_http/loki: otlp_http/loki:
endpoint: "http://loki:3100/otlp" endpoint: "http://loki:3100/otlp"
prometheus: prometheus:
endpoint: "0.0.0.0:8889" endpoint: "0.0.0.0:9464"
service: service:
extensions: [health_check] extensions: [health_check]
+4
View File
@@ -9,3 +9,7 @@ scrape_configs:
- job_name: 'otel-collector' - job_name: 'otel-collector'
static_configs: static_configs:
- targets: ['otel-collector:8889'] - targets: ['otel-collector:8889']
- job_name: 'otel-collector-metrics'
static_configs:
- targets: ['otel-collector:9464']