Фикс логгера
This commit is contained in:
+53
-33
@@ -18,12 +18,9 @@ from .storage.db import init_pool, close_pool
|
||||
from .telemetry import init_telemetry, INSTANCE_ID, meter, tracer
|
||||
|
||||
|
||||
# --- Логирование: структурный stdout, без содержимого сообщений ---
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
# Базовый логгер: реальный формат выставит telemetry.install_log_format()
|
||||
# при вызове init_telemetry(). Здесь — минимальный fallback для импорта.
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
|
||||
@@ -53,7 +50,7 @@ init_telemetry("messenger-api", "1.6.0")
|
||||
FastAPIInstrumentor.instrument_app(app)
|
||||
|
||||
|
||||
# --- Метрики HTTP из контракта observability.md ---
|
||||
# --- Метрики HTTP ---
|
||||
_http_counter = meter("messenger").create_counter(
|
||||
"http_requests_total",
|
||||
description="HTTP requests count",
|
||||
@@ -84,40 +81,63 @@ def custom_openapi():
|
||||
|
||||
app.openapi = custom_openapi
|
||||
|
||||
# Отдельный tracer для собственного span в middleware. Появляется как
|
||||
# child к server span FastAPI (он активен во время обработки запроса).
|
||||
_http_tracer = tracer("app.http")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def observability_middleware(request: Request, call_next):
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог + метрики."""
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог + метрики.
|
||||
|
||||
Лог event=http пишется ВНУТРИ активного span (`http.request`), иначе
|
||||
после await call_next() span FastAPI уже закрыт, и в лог попадёт
|
||||
trace_id=000… (это ломало корреляцию лог↔trace в Loki).
|
||||
"""
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.monotonic()
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
duration_s = time.monotonic() - started
|
||||
duration_ms = round(duration_s * 1000, 2)
|
||||
path = request.url.path
|
||||
route = _route_template(path)
|
||||
status_class = "%dxx" % (response.status_code // 100)
|
||||
route = _route_template(request.url.path)
|
||||
|
||||
# Только low-cardinality labels: method, route template, status class.
|
||||
_http_counter.add(
|
||||
1,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
_http_hist.record(
|
||||
duration_s,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
# Свой span, дочерний к FastAPI server span. Внутри него — вся обработка
|
||||
# запроса и запись структурированного лога с настоящим trace_id.
|
||||
with _http_tracer.start_as_current_span(
|
||||
"http.request",
|
||||
attributes={
|
||||
"http.method": request.method,
|
||||
"http.route": route,
|
||||
},
|
||||
) as span:
|
||||
response = await call_next(request)
|
||||
duration_s = time.monotonic() - started
|
||||
duration_ms = round(duration_s * 1000, 2)
|
||||
status_class = "%dxx" % (response.status_code // 100)
|
||||
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s",
|
||||
request.method, path, response.status_code,
|
||||
duration_ms, request_id, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
|
||||
_http_counter.add(
|
||||
1,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
_http_hist.record(
|
||||
duration_s,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
span.set_attribute("http.status_class", status_class)
|
||||
span.set_attribute("http.status_code", response.status_code)
|
||||
|
||||
# Лог ВНУТРИ span → record.trace_id валидный, Loki получает
|
||||
# корреляцию с Tempo.
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s "
|
||||
"request_id=%s instance_id=%s",
|
||||
request.method, request.url.path, response.status_code,
|
||||
duration_ms, request_id, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
# --- Обработчики ошибок (без изменений с lab5) ---
|
||||
|
||||
Reference in New Issue
Block a user