Python and FastAPI Structured Logging: from boundary to verified row
Use Python and FastAPI Structured Logging at a controlled application boundary, keep the event contract small, and verify a known outcome before building aggregate views.
- 1
Choose the outcome
Python API monitoring
- 2
Define the contract
route_template, method, and status_code
- 3
Instrument the boundary
Use the matched route path instead of the raw URL so identifiers do not create unbounded groups.
- 4
Verify the evidence
Exercise a known fixture, then inspect api_request_completed for one correctly typed terminal row.
Before you start
Prerequisites and boundaries
- telemetry-sh installed in the service environment
- TelemetryAsync initialized with a server-side API key
- A request ID supplied by trusted middleware or generated at ingress
Delivery setup
Install and initialize server-side
Initialize Telemetry for synchronous code or TelemetryAsync for asyncio code once per process with a server-side key. Keep ingestion credentials out of browser bundles, client-visible environment variables, source control, logs, and exception messages.
pip installation
python -m pip install telemetry-sh- 1Prepare one reusable server-side delivery client with bounded network behavior.
- 2Add the outcome event at the success, failure, retry, or timeout boundary.
- 3Send controlled fixtures and inspect the stored rows before enabling an alert.
Snippet
Start with one structured event
Add this shape where the workflow completes, fails, or retries. Then build the dashboard from real fields.
Python and FastAPI Structured Logging event
@app.middleware("http")
async def record_request(request, call_next):
started_at = time.perf_counter()
response = await call_next(request)
route = request.scope.get("route")
await telemetry.log("api_request_completed", {
"route_template": getattr(route, "path", "unmatched"),
"method": request.method,
"status_code": response.status_code,
"status": "failed" if response.status_code >= 500 else "success",
"latency_ms": round((time.perf_counter() - started_at) * 1000),
"request_id": request.headers.get("x-request-id"),
})
return responseEvent contract
route_template, method, and status_code
status, latency_ms, and error_type
request_id, environment, and release
Implementation checkpoints
Checkpoint 1
Use the matched route path instead of the raw URL so identifiers do not create unbounded groups.
Checkpoint 2
Await asynchronous ingestion after the response outcome is known and define failure behavior that will not hide the API response.
Checkpoint 3
Add exception-handler instrumentation for failures that bypass normal middleware completion.
Verification
Prove the event arrived
Run this after exercising known success and failure cases. Replace the fallback table name if your final event contract differs from the snippet.
Python and FastAPI Structured Logging verification query
SELECT *
FROM api_request_completed
ORDER BY timestamp_utc DESC
LIMIT 20;Implementation references
Review the event contract, data-safety guidance, and upstream primary documentation before enabling a new production path.
Production boundary
Keep the outcome event small and recoverable
This pattern provides
- A bounded, SQL-ready outcome beside the upstream workflow.
- Stable fields for dashboards, alerts, and cross-event correlation.
- A fixture-driven path for validating success, failure, retry, and timeout behavior.
This pattern does not provide
- An OTLP exporter, automatic collection pipeline, or replacement for detailed traces and diagnostic logs.
- Exactly-once delivery merely because the payload contains an event ID.
- Permission to collect raw provider payloads, user content, credentials, or regulated data.
Event schema starting points
Event contracts for this workflow
Review the row grain, emit boundary, required types, privacy classes, example payload, and validation checklist before adapting a query or snippet to production.
Related product capability
Continue this workflow in Alerts
Promote the reviewed reliability query into an owned threshold and response workflow.
Related SQL recipes
Answer the next question with SQL
Run the query against the structured fields from this workflow, inspect the example result, and turn a useful answer into a dashboard or alert.
Calculate API Error Rate by Route
Which API routes have the highest meaningful 5xx error rate?
Open recipeCalculate p50, p95, and p99 API Latency
Which endpoints have the worst tail latency?
Open recipeCalculate API Timeout Rate by Route
Which API routes time out often enough to affect users?
Open recipeCompare Dependency p95 Latency
Which downstream dependencies have the worst tail latency and failure rate?
Open recipeRank Error Fingerprints by Customer Impact
Which error groups affect the most customer accounts?
Open recipeBrowse by implementation family
Compare related integration patterns
Templates to pair with this integration
More integrations
Node.js and Express Structured Logging
Instrument Express route outcomes with stable route templates, status codes, request latency, and safe correlation fields.
Open guideElixir Phoenix Telemetry Integration
Attach to Phoenix request lifecycle events and forward a bounded terminal request outcome without copying connection data, parameters, or exception text.
Open guideSpring Boot Structured Event Monitoring
Record Spring MVC and scheduled-workflow outcomes through Telemetry's HTTP API with stable routes, latency, status, and trace context.
Open guide