Фикс логгера
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
|
from .telemetry import init_telemetry, INSTANCE_ID, meter, tracer
|
||||||
|
|
||||||
|
|
||||||
# --- Логирование: структурный stdout, без содержимого сообщений ---
|
# Базовый логгер: реальный формат выставит telemetry.install_log_format()
|
||||||
logging.basicConfig(
|
# при вызове init_telemetry(). Здесь — минимальный fallback для импорта.
|
||||||
level=logging.INFO,
|
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
||||||
stream=sys.stdout,
|
|
||||||
)
|
|
||||||
logger = logging.getLogger("app")
|
logger = logging.getLogger("app")
|
||||||
|
|
||||||
|
|
||||||
@@ -53,7 +50,7 @@ init_telemetry("messenger-api", "1.6.0")
|
|||||||
FastAPIInstrumentor.instrument_app(app)
|
FastAPIInstrumentor.instrument_app(app)
|
||||||
|
|
||||||
|
|
||||||
# --- Метрики HTTP из контракта observability.md ---
|
# --- Метрики HTTP ---
|
||||||
_http_counter = meter("messenger").create_counter(
|
_http_counter = meter("messenger").create_counter(
|
||||||
"http_requests_total",
|
"http_requests_total",
|
||||||
description="HTTP requests count",
|
description="HTTP requests count",
|
||||||
@@ -84,40 +81,63 @@ def custom_openapi():
|
|||||||
|
|
||||||
app.openapi = custom_openapi
|
app.openapi = custom_openapi
|
||||||
|
|
||||||
|
# Отдельный tracer для собственного span в middleware. Появляется как
|
||||||
|
# child к server span FastAPI (он активен во время обработки запроса).
|
||||||
|
_http_tracer = tracer("app.http")
|
||||||
|
|
||||||
|
|
||||||
@app.middleware("http")
|
@app.middleware("http")
|
||||||
async def observability_middleware(request: Request, call_next):
|
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_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||||
request.state.request_id = request_id
|
request.state.request_id = request_id
|
||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
response = await call_next(request)
|
route = _route_template(request.url.path)
|
||||||
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)
|
|
||||||
|
|
||||||
# Только low-cardinality labels: method, route template, status class.
|
# Свой span, дочерний к FastAPI server span. Внутри него — вся обработка
|
||||||
_http_counter.add(
|
# запроса и запись структурированного лога с настоящим trace_id.
|
||||||
1,
|
with _http_tracer.start_as_current_span(
|
||||||
{"http.method": request.method, "http.route": route,
|
"http.request",
|
||||||
"http.status_class": status_class},
|
attributes={
|
||||||
)
|
"http.method": request.method,
|
||||||
_http_hist.record(
|
"http.route": route,
|
||||||
duration_s,
|
},
|
||||||
{"http.method": request.method, "http.route": route,
|
) as span:
|
||||||
"http.status_class": status_class},
|
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(
|
response.headers["X-Request-Id"] = request_id
|
||||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s",
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||||
request.method, path, response.status_code,
|
|
||||||
duration_ms, request_id, INSTANCE_ID,
|
_http_counter.add(
|
||||||
)
|
1,
|
||||||
return response
|
{"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) ---
|
# --- Обработчики ошибок (без изменений с lab5) ---
|
||||||
|
|||||||
Reference in New Issue
Block a user