:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(llm-gateway): log unhandled exceptions and their 500 status (#81041)
Michael Matlokaabeca6507eec
diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.pyindex d4874834e8fd..48e3da43467d 100644--- a/services/llm-gateway/src/llm_gateway/main.py+++ b/services/llm-gateway/src/llm_gateway/main.py@@ -4,6 +4,7 @@ import asyncioimport loggingimport osimport time+import tracebackimport uuidfrom collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanager@@ -16,6 +17,7 @@ from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponsefrom redis.asyncio import Redisfrom starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint+from starlette.requests import ClientDisconnectfrom starlette.responses import Responsefrom starlette.types import ASGIApp@@ -78,26 +80,52 @@ class RequestLoggingMiddleware(BaseHTTPMiddleware):structlog.contextvars.bind_contextvars(request_id=request_id)start_time = time.monotonic()+ # Stays None for a client that went away: CancelledError is a BaseException and escapes the+ # except clauses below, and ClientDisconnect is re-raised untouched. Neither produced a+ # status code, so logging one would invent a response the client never received.+ status_code: int | None = None- response = await call_next(request)- response.headers["x-request-id"] = request_id-- duration_ms = (time.monotonic() - start_time) * 1000-- if request.url.path not in ("/_liveness", "/_readiness", "/metrics"):- logger.info(- "request",+ try:+ response = await call_next(request)+ status_code = response.status_code+ response.headers["x-request-id"] = request_id+ if hasattr(request.app.state, "db_pool"):+ update_db_pool_metrics(request.app.state.db_pool)+ return response+ except ClientDisconnect:+ # A plain Exception, so without this it would take the clause below and report a 500 the+ # aborting client never saw. The rest of the service treats a disconnect as ordinary+ # traffic too (see the disconnect counters in api/handler.py and api/anthropic.py).+ raise+ except Exception as exc:+ # Starlette's ServerErrorMiddleware sits above this middleware, so an exception escaping+ # call_next is the 500 the client gets. Without logging it here the request would leave+ # no line at all, and a status-code aggregation would read the failure as no traffic.+ status_code = 500+ logger.error(+ "unhandled_exception",method=request.method,path=request.url.path,- status_code=response.status_code,- duration_ms=round(duration_ms, 2),+ error_type=type(exc).__name__,+ # The configured processor chain has no format_exc_info, so exc_info would render as+ # a repr of the tuple instead of a traceback. Pass the formatted text explicitly,+ # under the key structlog's own exception renderer would use.+ exception=traceback.format_exc(),)-- if hasattr(request.app.state, "db_pool"):- update_db_pool_metrics(request.app.state.db_pool)-- structlog.contextvars.unbind_contextvars("request_id")- return response+ raise+ finally:+ duration_ms = (time.monotonic() - start_time) * 1000++ if status_code is not None and request.url.path not in ("/_liveness", "/_readiness", "/metrics"):+ logger.info(+ "request",+ method=request.method,+ path=request.url.path,+ status_code=status_code,+ duration_ms=round(duration_ms, 2),+ )++ structlog.contextvars.unbind_contextvars("request_id")async def init_redis(url: str | None) -> Redis[bytes] | None:diff --git a/services/llm-gateway/tests/test_main.py b/services/llm-gateway/tests/test_main.pyindex d102485cf456..2cb76e6d3458 100644--- a/services/llm-gateway/tests/test_main.py+++ b/services/llm-gateway/tests/test_main.py@@ -1,9 +1,14 @@import osimport pytest+import structlog+from fastapi import Depends, FastAPI+from fastapi.testclient import TestClient+from starlette.requests import ClientDisconnect+from structlog.testing import capture_logsfrom llm_gateway.config import Settings, get_settings-from llm_gateway.main import export_provider_credentials+from llm_gateway.main import RequestLoggingMiddleware, export_provider_credentials_EXPORTED_ENV_VARS = ("ANTHROPIC_API_KEY",@@ -151,3 +156,72 @@ class TestExportProviderCredentials:export_provider_credentials(settings)assert os.environ["OPENAI_BASE_URL"] == "https://eu.api.openai.com/v1"+++def _middleware_test_client() -> TestClient:+ app = FastAPI()+ app.add_middleware(RequestLoggingMiddleware)++ def refuse_to_read_postgres() -> None:+ raise RuntimeError("permission denied for table posthog_team")++ @app.get("/ok")+ def ok() -> dict[str, bool]:+ return {"ok": True}++ @app.get("/raises", dependencies=[Depends(refuse_to_read_postgres)])+ def raises() -> dict[str, bool]:+ return {"ok": True}++ def abandon_request() -> None:+ raise ClientDisconnect++ @app.get("/disconnects", dependencies=[Depends(abandon_request)])+ def disconnects() -> dict[str, bool]:+ return {"ok": True}++ return TestClient(app, raise_server_exceptions=False)+++class TestRequestLoggingMiddleware:+ def test_every_request_gets_one_request_line_with_the_status_the_client_saw(self) -> None:+ # Guards the regression where a raising dependency leaves no request line, which makes a+ # status-code aggregation over these logs read a total outage as zero traffic.+ client = _middleware_test_client()++ with capture_logs() as logs:+ assert client.get("/ok").status_code == 200+ assert client.get("/raises").status_code == 500++ assert [(log["path"], log["status_code"]) for log in logs if log["event"] == "request"] == [+ ("/ok", 200),+ ("/raises", 500),+ ]++ def test_unhandled_exception_is_logged_at_error_level_with_its_traceback(self) -> None:+ client = _middleware_test_client()++ with capture_logs(processors=[structlog.contextvars.merge_contextvars]) as logs:+ client.get("/raises")++ errors = [log for log in logs if log["event"] == "unhandled_exception"]+ assert len(errors) == 1+ assert errors[0]["log_level"] == "error"+ assert errors[0]["method"] == "GET"+ assert errors[0]["path"] == "/raises"+ assert errors[0]["error_type"] == "RuntimeError"+ assert "permission denied for table posthog_team" in errors[0]["exception"]++ request_lines = [log for log in logs if log["event"] == "request"]+ assert errors[0]["request_id"] == request_lines[0]["request_id"]++ def test_client_disconnect_logs_neither_an_error_nor_a_status(self) -> None:+ # ClientDisconnect is a plain Exception, so a client aborting mid-body would otherwise be+ # reported as a 500 it never saw, and every abort would raise an error-level event.+ client = _middleware_test_client()++ with capture_logs() as logs:+ client.get("/disconnects")++ assert [log for log in logs if log["event"] == "unhandled_exception"] == []+ assert [log for log in logs if log["event"] == "request"] == []