Middleware
Enrich request spans in Flask, FastAPI, and Django with the Sophonz Python SDK — baggage and session.id, client IP, user-agent, custom attributes, and error handlers.
The SDK ships request helpers for Flask, FastAPI (and any Starlette app), and Django — the Python counterparts of sophonzExpressMiddleware and setupExpressErrorHandler. Server spans come from the OpenTelemetry instrumentation for each framework; the helpers copy baggage, the client IP, the user agent, and your own attributes onto every span of the request, and record exceptions that escape a route.
Each helper lives in its own module and imports its framework only when that module is used. Install the matching extra (sophonz-opentelemetry[flask], [fastapi], or [django]) so the framework instrumentation is present.
Flask
from flask import Flask
from sophonz.opentelemetry import init
from sophonz.opentelemetry.flask import setup_flask_error_handler, sophonz_flask_middleware
init(service="checkout-api")
app = Flask(__name__)
sophonz_flask_middleware(app)
setup_flask_error_handler(app)
@app.get("/")
def index():
return "ok"sophonz_flask_middleware registers a before_request hook. It also instruments the app with FlaskInstrumentor when it is not already instrumented, so it works whether init() ran before or after the app was created (pass instrument=False to skip that).
Per-request attributes via a function — it receives the Flask request:
sophonz_flask_middleware(
app,
attributes=lambda request: {"enduser.id": request.headers.get("x-user-id", "")},
)FastAPI
from fastapi import FastAPI
from sophonz.opentelemetry import init
from sophonz.opentelemetry.fastapi import setup_fastapi_error_handler, sophonz_fastapi_middleware
init(service="checkout-api")
app = FastAPI()
sophonz_fastapi_middleware(app)
setup_fastapi_error_handler(app)
@app.get("/")
async def index():
return {"status": "ok"}sophonz_fastapi_middleware adds SophonzASGIMiddleware, a pure ASGI middleware (streaming responses and background tasks are unaffected), and instruments the app with FastAPIInstrumentor when needed. The attributes function receives the ASGI scope. The middleware also flushes telemetry when the application finishes its lifespan shutdown; see Graceful shutdown.
Both helpers append their middleware innermost instead of using add_middleware, which would make it outermost. That keeps enrichment and exception recording inside the OpenTelemetry server span no matter where you call them relative to CORSMiddleware or other middleware. Call them before the app starts serving.
For a plain Starlette app, use the same helpers with instrument=False, and create the server spans with the Starlette instrumentation (opentelemetry-instrumentation-starlette):
from starlette.applications import Starlette
from sophonz.opentelemetry.fastapi import setup_fastapi_error_handler, sophonz_fastapi_middleware
app = Starlette(routes=routes)
sophonz_fastapi_middleware(app, instrument=False)
setup_fastapi_error_handler(app)Django
Add SophonzMiddleware to MIDDLEWARE. It works under WSGI and ASGI. The Django instrumentation inserts its own middleware, which creates the server span, at the top of the list, so SophonzMiddleware can go anywhere below it. Placing it last is recommended: it then reads REMOTE_ADDR after any middleware that rewrites it, and, since Django calls process_exception from the bottom up, sees a view's exception before other middleware turn it into a response.
# settings.py
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
# ...
"sophonz.opentelemetry.django.SophonzMiddleware",
]
# optional
SOPHONZ_MIDDLEWARE = {
"capture_client_ip": True,
"capture_user_agent": True,
"capture_baggage": True,
# a dict, or the dotted path of a function receiving the HttpRequest
"attributes": "shop.telemetry.request_attributes",
}SophonzMiddleware.process_exception records exceptions raised by views. The Django instrumentation is loaded by init() (set DJANGO_SETTINGS_MODULE first); sophonz.opentelemetry.django.instrument_django() does it explicitly if you need to. The SOPHONZ_MIDDLEWARE setting is read once, when Django creates the middleware.
NOTE — Initialize the SDK before loading the framework
Call init() before the framework and database drivers are imported, so the instrumentations patch them. For Django, do it in manage.py, wsgi.py, and asgi.py after DJANGO_SETTINGS_MODULE is set. See the examples.
Options
sophonz_flask_middleware, sophonz_fastapi_middleware / SophonzASGIMiddleware, and SOPHONZ_MIDDLEWARE for Django accept the same options:
| Option | Type | Default | Description |
|---|---|---|---|
capture_baggage | bool | True | Copy every baggage entry onto the request's spans, prefixed with baggage.. |
capture_client_ip | bool | True | Capture the client IP as http.client.ip (the peer address; use your framework's proxy support to trust X-Forwarded-For). |
capture_user_agent | bool | True | Capture the user-agent header as http.user_agent. |
attributes | dict | Callable[[request], dict] | — | Extra attributes — a static dict, or a function receiving the framework request (Flask request, ASGI scope, Django HttpRequest). |
instrument | bool | True | Flask and FastAPI only: instrument the app if it is not already. |
Attributes are applied to the server span and, through set_trace_attributes(), to every span started while handling the request — database and HTTP client spans included. An attribute a span already has is not overwritten.
NOTE — Telemetry never breaks requests
Enrichment runs inside a try/except. If it fails for any reason — an attributes function raising, for example — the request continues normally. The helper then adds none of its attributes to that request; baggage is still copied by the SDK itself.
Baggage and session.id
The SDK itself, not only the middleware, copies every W3C baggage entry onto every span as baggage.<key>. The session.id entry that the Sophonz browser SDK sends is also copied as session.id, so a browser session and the server and database spans it caused share one queryable attribute. Other keys can be promoted with promote_baggage_keys:
init(service="checkout-api", promote_baggage_keys=["session.id", "tenant.id"])CAUTION — Baggage is sent onward
Baggage is propagated to every downstream service your app calls. Do not put sensitive data in it.
Error handlers
Register the error handler after creating the app. It records exceptions that escape a route — the ones that become HTTP 500 — as an exception event on the request span and sets its status to ERROR. Handled errors (FastAPI's HTTPException, Flask's abort(404)) are not recorded, and Django's SophonzMiddleware skips Http404, PermissionDenied, BadRequest, and SuspiciousOperation.
The framework instrumentations already record escaping exceptions on their server spans; the handlers detect that, add only exception.mechanism (flask, asgi, or django), and do not record them a second time. Without the instrumentation, the handler records the exception itself.
NOTE — Django and Http404
The Django instrumentation records every exception a view raises, Http404 included, on the server span and marks it ERROR, independently of SophonzMiddleware. Return a 404 response instead of raising Http404 where that matters.
With error_log_capture (on by default), the failed span also produces one error log record linked to the trace.
Manual recording
Record a handled error anywhere with record_exception:
from sophonz.opentelemetry import record_exception
try:
sync_inventory()
except Exception as exc:
record_exception(exc, attributes={"job.name": "nightly-sync"})It records on the current span, or on span= when given. With no span in context it creates a short span named after the exception type.
See the Framework Guides for complete application wiring, and the API Reference for the full signatures.