Framework Guides

Wire the Sophonz Python SDK into Flask, FastAPI, and Django applications and their production servers — gunicorn workers, uvicorn and lifespan, Django entrypoints, middleware order, and error handling.

Each framework has one place where init() belongs and one server process model that decides when it runs. This page covers both for Flask, FastAPI, and Django, following the layout of the Sophonz sample servers: a telemetry.py that starts the SDK, an entrypoint that imports it first, and an application factory that adds the request helpers.

The rules that apply everywhere

  • Start the SDK before the framework and database driver are imported. init() loads the OpenTelemetry instrumentations, which patch the framework and driver modules. Classes and connections created before that are not traced, or are traced without your instrumentations configuration.
  • Start it once per process, in the process that serves requests. OpenTelemetry sets its global providers only once. A second init() in the same process returns False and logs a warning.
  • Under a pre-fork server, start it in each worker. Exporters use background threads, and threads do not survive fork().
ServerWhere init() runsFlush on shutdown
gunicorn, no --preloadEach worker, when it imports the WSGI moduleSDK signal handler, then worker_exit
gunicorn, --preloadThe master, before forkingworker_exit (see Installation)
uvicorn, one processThe server process, when it imports the appSDK signal handler, then lifespan shutdown
uvicorn --workers NEach worker processSDK signal handler, then lifespan shutdown
manage.py runserver --noreloadThe runserver processSDK signal handler

The sample servers run gunicorn without --preload and one uvicorn process per pod, and the rest of this page assumes the same.

Flask

Install the extras for Flask and your database driver:

pip install "sophonz-opentelemetry[flask,psycopg]" flask gunicorn "psycopg[binary,pool]"

Layout

myservice/
  telemetry.py      # init()
  wsgi.py           # imports telemetry first, then builds the app
  app.py            # create_app(): helpers, routes, error handlers
gunicorn.conf.py

telemetry.py holds the SDK configuration, so every entrypoint (the WSGI module, a CLI, a test) starts it the same way:

# myservice/telemetry.py
import os
 
from sophonz.opentelemetry import init
 
SERVICE_NAME = os.getenv("OTEL_SERVICE_NAME", "checkout-api")
 
 
def setup_telemetry() -> bool:
    return init(
        service=SERVICE_NAME,
        api_key=os.getenv("SOPHONZ_API_KEY"),
        instrumentations={
            "psycopg": {"enable_commenter": True},
        },
    )

The WSGI module calls it before anything imports Flask or psycopg:

# myservice/wsgi.py
import logging
 
from myservice.telemetry import setup_telemetry
 
setup_telemetry()
 
logging.basicConfig(level=logging.INFO)
 
from myservice.app import create_app  # noqa: E402
 
app = create_app()

logging.basicConfig after init() is fine: the SDK keeps its OTLP handler on the root logger through basicConfig, dictConfig, and fileConfig.

Application factory

# myservice/app.py
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException, InternalServerError
from werkzeug.middleware.proxy_fix import ProxyFix
 
from sophonz.opentelemetry.flask import setup_flask_error_handler, sophonz_flask_middleware
 
 
def create_app() -> Flask:
    app = Flask(__name__)
 
    # Behind a reverse proxy: request.remote_addr, and so http.client.ip,
    # comes from X-Forwarded-For.
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
 
    sophonz_flask_middleware(app)
    setup_flask_error_handler(app)
 
    @app.get("/api/error")
    def error():
        raise RuntimeError("Intentional error")
 
    @app.errorhandler(InternalServerError)
    def internal_error(exc):
        original = exc.original_exception or exc
        return jsonify(error=str(original)), 500
 
    @app.errorhandler(HTTPException)
    def http_error(exc):
        return jsonify(error=exc.description), exc.code
 
    return app
  • sophonz_flask_middleware registers a before_request hook that puts baggage, http.client.ip, http.user_agent, and your attributes on every span of the request. It also instruments this app object if it is not already instrumented.
  • setup_flask_error_handler listens to Flask's got_request_exception signal. The signal fires before your errorhandler runs, so a custom 500 handler does not hide the exception from the trace.
  • abort(404) and other HTTPExceptions do not fire the signal and are not recorded.

gunicorn

# gunicorn.conf.py
import os
 
bind = f"0.0.0.0:{os.getenv('PORT', '8000')}"
workers = int(os.getenv("WEB_CONCURRENCY", "2"))
worker_class = "gthread"
threads = int(os.getenv("GUNICORN_THREADS", "4"))
timeout = 30
graceful_timeout = 20
# No preload_app: each worker imports wsgi.py, and starts the SDK, after the fork.
 
 
def worker_exit(server, worker):
    # Imported here: the master process never starts the SDK.
    from sophonz.opentelemetry import shutdown
 
    shutdown()
gunicorn -c gunicorn.conf.py myservice.wsgi:app

On SIGTERM, the SDK's handler in each worker flushes, then hands over to gunicorn's graceful shutdown; worker_exit flushes whatever was recorded while requests drained.

SQL comments from Flask

The Flask instrumentation adds framework, controller, and route tags to SQLCommenter comments when commenting is enabled on the driver. The comment then carries more than the trace context, and its text changes per route. To keep only traceparent, turn it off on the Flask side:

instrumentations={
    "psycopg": {"enable_commenter": True},
    "flask": {"enable_commenter": False},
}

See Database Tracing for the driver options.

FastAPI

pip install "sophonz-opentelemetry[fastapi,psycopg]" fastapi uvicorn "psycopg[binary,pool]"

Entrypoint

# myservice/main.py
import logging
 
from myservice.telemetry import setup_telemetry
 
setup_telemetry()
 
logging.basicConfig(level=logging.INFO)
 
from myservice.app import create_app  # noqa: E402
 
app = create_app()

Create the FastAPI object after init(). The FastAPI instrumentation applies your instrumentations["fastapi"] settings, and the advanced network capture hooks, to apps constructed after it loads. sophonz_fastapi_middleware still instruments an app created earlier, but with the instrumentation's defaults.

Application, middleware, lifespan

# myservice/app.py
import contextlib
 
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from psycopg_pool import AsyncConnectionPool
 
from sophonz.opentelemetry.fastapi import setup_fastapi_error_handler, sophonz_fastapi_middleware
 
 
def create_app() -> FastAPI:
    pool = AsyncConnectionPool("postgresql://app:app@localhost:5432/app", open=False)
 
    @contextlib.asynccontextmanager
    async def lifespan(_app: FastAPI):
        await pool.open()
        try:
            yield
        finally:
            await pool.close()
 
    app = FastAPI(lifespan=lifespan)
 
    setup_fastapi_error_handler(app)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["https://app.example.com"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["traceparent", "tracestate", "baggage", "content-type"],
    )
    sophonz_fastapi_middleware(app)
 
    @app.get("/api/error")
    async def error():
        raise RuntimeError("Intentional error")
 
    @app.exception_handler(Exception)
    async def unhandled(request: Request, exc: Exception):
        headers = {}
        if origin := request.headers.get("origin"):
            headers = {"Access-Control-Allow-Origin": origin, "Vary": "Origin"}
        return JSONResponse({"error": str(exc)}, status_code=500, headers=headers)
 
    return app

Middleware order. Starlette's add_middleware makes each new middleware the outermost layer. The two Sophonz helpers do the opposite: they append their middleware innermost, so it always runs inside the OpenTelemetry server span, whatever order you register things in. With the code above the stack is, from the outside in:

  1. The OpenTelemetry server middleware (added by the instrumentation)
  2. CORSMiddleware
  3. SophonzExceptionMiddleware (from setup_fastapi_error_handler)
  4. SophonzASGIMiddleware (from sophonz_fastapi_middleware)

Call both helpers before the app starts serving; adding middleware afterwards raises RuntimeError.

Errors. SophonzExceptionMiddleware records an exception that escapes a route, then re-raises it. HTTPException and anything an exception handler turns into a response are not recorded. Starlette answers unhandled exceptions from ServerErrorMiddleware, which sits outside every user middleware, including CORSMiddleware. A browser then sees a CORS failure instead of the 500, which is why the handler above adds the CORS headers itself.

Lifespan. SophonzASGIMiddleware flushes telemetry after the application reports lifespan shutdown complete, so spans recorded while uvicorn drained requests are exported before the process exits.

Async database access

The trace context follows await and asyncio.gather. Two queries started concurrently inside one request are both children of that request's span:

import asyncio
 
 
@app.get("/api/users/{user_id}")
async def get_user(user_id: int):
    async def find_user():
        async with pool.connection() as conn:
            cur = await conn.execute("SELECT id, email FROM users WHERE id = %s", (user_id,))
            return await cur.fetchone()
 
    async def find_posts():
        async with pool.connection() as conn:
            cur = await conn.execute("SELECT id, title FROM posts WHERE author_id = %s", (user_id,))
            return await cur.fetchall()
 
    user, posts = await asyncio.gather(find_user(), find_posts())
    return {"user": user, "posts": posts}

uvicorn

uvicorn myservice.main:app --host 0.0.0.0 --port 8000 \
  --loop asyncio --proxy-headers --forwarded-allow-ips "*" \
  --timeout-graceful-shutdown 20
  • No --reload. The reloader restarts the serving process on every file change, and a new SDK with it. The sample servers run without it.
  • --loop asyncio. experimental_exception_capture hooks the standard asyncio event loop's exception handler. uvloop is not covered.
  • --proxy-headers makes the client address, and so http.client.ip, come from X-Forwarded-For when a trusted proxy sets it.
  • --workers N starts N processes that each import the app and start their own SDK. In containers, the sample servers run one process per pod and scale with replicas instead.

Fewer spans per request

The ASGI instrumentation records an http receive and http send child span for each message of a request. To keep only the server span:

instrumentations={"fastapi": {"exclude_spans": ["receive", "send"]}}

CAUTION — Bodies are captured on those spans

With advanced_network_capture, FastAPI request and response bodies are recorded on the http receive and http send spans. Excluding those spans also turns body capture off. Headers are still captured on the server span.

Django

pip install "sophonz-opentelemetry[django,psycopg]" django gunicorn "psycopg[binary]"

Entrypoints

The Django instrumentation reads your settings when it loads, so DJANGO_SETTINGS_MODULE must be set before init(). Put the SDK start-up in one module and call it from every entrypoint that serves requests:

# mysite/telemetry.py
import os
 
from sophonz.opentelemetry import init, is_initialized
 
 
def setup_telemetry() -> bool:
    if is_initialized():
        return False
    return init(
        service=os.getenv("OTEL_SERVICE_NAME", "mysite"),
        api_key=os.getenv("SOPHONZ_API_KEY"),
        instrumentations={"psycopg": {"enable_commenter": True}},
    )
# mysite/wsgi.py — gunicorn mysite.wsgi
import os
 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
 
from mysite.telemetry import setup_telemetry  # noqa: E402
 
setup_telemetry()
 
from django.core.wsgi import get_wsgi_application  # noqa: E402
 
application = get_wsgi_application()
# mysite/asgi.py — uvicorn mysite.asgi:application
import os
 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
 
from mysite.telemetry import setup_telemetry  # noqa: E402
 
setup_telemetry()
 
from django.core.asgi import get_asgi_application  # noqa: E402
 
application = get_asgi_application()
# manage.py
import os
import sys
 
 
def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    # Only the development server serves requests; migrate and other
    # commands run without the SDK.
    if len(sys.argv) > 1 and sys.argv[1] == "runserver":
        from mysite.telemetry import setup_telemetry
 
        setup_telemetry()
 
    from django.core.management import execute_from_command_line
 
    execute_from_command_line(sys.argv)
 
 
if __name__ == "__main__":
    main()

Run the development server with python manage.py runserver --noreload, so the SDK starts in the process that serves requests. runserver also loads WSGI_APPLICATION; the is_initialized() check keeps that second call quiet.

gunicorn uses the same gunicorn.conf.py as Flask, with gunicorn -c gunicorn.conf.py mysite.wsgi.

Settings

# mysite/settings.py (excerpt)
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.middleware.common.CommonMiddleware",
    # ... middleware that rewrites REMOTE_ADDR goes above this line
    "sophonz.opentelemetry.django.SophonzMiddleware",
]
 
SOPHONZ_MIDDLEWARE = {
    "attributes": "mysite.telemetry.request_attributes",  # or a dict
}
 
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"class": "logging.StreamHandler"}},
    "root": {"handlers": ["console"], "level": "INFO"},
}
# mysite/telemetry.py (continued)
def request_attributes(request):
    user = getattr(request, "user", None)
    if user is None or not user.is_authenticated:
        return {}
    return {"enduser.id": str(user.pk)}

If the attributes function raises, none of the attributes are added for that request; the request itself continues.

  • The Django instrumentation inserts its own middleware at the top of MIDDLEWARE when it loads; that middleware starts the server span.
  • SophonzMiddleware reads REMOTE_ADDR and the user agent when the request reaches it. Middleware that sets REMOTE_ADDR from X-Forwarded-For must come before it.
  • Django calls process_exception from the bottom of the list up. Placing SophonzMiddleware last lets it record a view's exception before any other middleware turns it into a response.
  • LOGGING is applied through dictConfig, which keeps the SDK's OTLP handler on the root logger.

Errors

SophonzMiddleware.process_exception records exceptions raised by views, except those Django turns into 4xx responses: Http404, PermissionDenied, BadRequest, and SuspiciousOperation.

NOTE — The Django instrumentation records every view exception

The Django instrumentation's own middleware records any exception a view raises on the server span, Http404 included, and sets the span status to ERROR. With error_log_capture on, those spans also produce an error log record. Return a 404 response instead of raising Http404 where that noise matters.

ORM

Django's PostgreSQL backend uses psycopg, so the psycopg instrumentation produces a client span per ORM query and adds the SQL comment. Keep commenting on the driver only; turning on the Django instrumentation's is_sql_commentor_enabled as well would add a second comment. See Database Tracing.

Under uvicorn

Django's ASGI handler does not implement lifespan events, so nothing flushes after uvicorn has drained requests. The SDK's signal handler flushes when the signal arrives, but spans that end during the drain can miss the final export. Prefer gunicorn with worker_exit for Django, or lower OTEL_BSP_SCHEDULE_DELAY (5000 ms by default).

Scripts and one-off jobs

A command-line job has no server to hand a signal to. Start the SDK first, and call shutdown() when the work is done so the last batch is exported before the interpreter exits:

import os
 
from sophonz.opentelemetry import init, shutdown, trace
 
init(service="nightly-sync", api_key=os.getenv("SOPHONZ_API_KEY"))
 
tracer = trace.get_tracer("nightly-sync")
 
try:
    with tracer.start_as_current_span("sync-inventory"):
        run_sync()
finally:
    shutdown()

Next steps

  • Middleware — every option of the request helpers.
  • Instrumentation — what is traced automatically, logs, exceptions, custom spans.
  • Deployment — containers, Kubernetes, and graceful shutdown.

TIP — This is just the beginning

Now ship your app. Sophonz surfaces the problems real users hit — so your app evolves on its own.