Examples

Complete Flask, FastAPI, and Django servers with the Sophonz Python SDK, laid out like the Sophonz sample servers — SDK start-up before imports, request helpers, CORS for browser traces, PostgreSQL with SQLCommenter, logging, and error handling.

Three small servers with the same API and the same telemetry: a trace started in the browser continues through the framework into PostgreSQL, every span carries the browser's session.id, logs are linked to the trace, and failing routes are recorded once. Each follows the layout of the Sophonz sample servers: telemetry.py starts the SDK, the entrypoint imports it before anything else, and the application is built afterwards.

Database

All three servers use the same two tables. Start a local PostgreSQL and create them:

docker run -d --name example-pg -p 5432:5432 \
  -e POSTGRES_USER=app -e POSTGRES_PASSWORD=app -e POSTGRES_DB=app \
  postgres:16-alpine -c log_statement=all
CREATE TABLE users (
  id serial PRIMARY KEY,
  email text UNIQUE NOT NULL,
  name text NOT NULL
);
 
CREATE TABLE posts (
  id serial PRIMARY KEY,
  author_id integer NOT NULL REFERENCES users (id),
  title text NOT NULL,
  body text NOT NULL
);

log_statement=all prints each statement in the container log, so you can see the traceparent comment arrive.

Servers

myservice/
  __init__.py       # empty
  telemetry.py
  app.py
  wsgi.py
gunicorn.conf.py
pip install "sophonz-opentelemetry[flask,psycopg]" flask flask-cors gunicorn "psycopg[binary,pool]"
# myservice/telemetry.py
import os
 
from sophonz.opentelemetry import init
 
SERVICE_NAME = os.getenv("OTEL_SERVICE_NAME", "example-flask")
 
# Keep only traceparent in the SQL comment; pg_tracing reads nothing else.
PSYCOPG = {
    "enable_commenter": True,
    "commenter_options": {
        "db_driver": False,
        "dbapi_threadsafety": False,
        "dbapi_level": False,
        "libpq_version": False,
        "driver_paramstyle": False,
    },
}
 
 
def setup_telemetry() -> bool:
    return init(
        service=SERVICE_NAME,
        api_key=os.getenv("SOPHONZ_API_KEY"),
        advanced_network_capture=True,
        instrumentations={
            "psycopg": PSYCOPG,
            # Flask would add framework/controller/route tags to the comment.
            "flask": {"enable_commenter": False},
        },
    )
# myservice/app.py
import logging
import os
 
import psycopg
from flask import Flask, jsonify, request
from flask_cors import CORS
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
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
 
logger = logging.getLogger("myservice")
 
 
def create_app() -> Flask:
    app = Flask(__name__)
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
 
    CORS(
        app,
        origins=os.getenv("CORS_ORIGINS", "http://localhost:3000").split(","),
        supports_credentials=True,
        allow_headers=["content-type", "traceparent", "tracestate", "baggage"],
    )
 
    # baggage.*, session.id, client IP, and user agent on every span of a
    # request; exceptions escaping a route recorded once.
    sophonz_flask_middleware(app)
    setup_flask_error_handler(app)
 
    # One pool per gunicorn worker, created after the SDK started.
    pool = ConnectionPool(
        os.environ["DATABASE_URL"],
        min_size=1,
        max_size=int(os.getenv("DB_POOL_SIZE", "5")),
        kwargs={"autocommit": True, "row_factory": dict_row},
        open=False,
    )
 
    def connection():
        if pool.closed:
            pool.open(wait=False)
        return pool.connection()
 
    @app.get("/health")
    def health():
        return jsonify(status="ok")
 
    @app.get("/api/users")
    def list_users():
        with connection() as conn:
            users = conn.execute("SELECT id, email, name FROM users ORDER BY id").fetchall()
        logger.info("listed users", extra={"count": len(users)})
        return jsonify(users)
 
    @app.get("/api/users/<int:user_id>")
    def get_user(user_id):
        with connection() as conn:
            user = conn.execute(
                "SELECT id, email, name FROM users WHERE id = %s", (user_id,)
            ).fetchone()
            if user is None:
                return jsonify(error="User not found"), 404
            posts = conn.execute(
                "SELECT id, title, body FROM posts WHERE author_id = %s ORDER BY id", (user_id,)
            ).fetchall()
        return jsonify({**user, "posts": posts})
 
    @app.post("/api/users")
    def create_user():
        payload = request.get_json(silent=True) or {}
        if not payload.get("email") or not payload.get("name"):
            return jsonify(error="email and name are required"), 400
        try:
            with connection() as conn:
                user = conn.execute(
                    "INSERT INTO users (email, name) VALUES (%s, %s) RETURNING id, email, name",
                    (payload["email"], payload["name"]),
                ).fetchone()
        except psycopg.errors.UniqueViolation:
            return jsonify(error="email already exists"), 409
        logger.info("created user", extra={"user_id": user["id"]})
        return jsonify(user), 201
 
    @app.get("/api/error")
    def error():
        raise RuntimeError("Intentional error from /api/error")
 
    # Runs after got_request_exception fired, so the span already has the exception.
    @app.errorhandler(InternalServerError)
    def internal_error(exc):
        return jsonify(error=str(exc.original_exception or exc)), 500
 
    @app.errorhandler(HTTPException)
    def http_error(exc):
        return jsonify(error=exc.description), exc.code
 
    return app
# myservice/wsgi.py
import logging
import os
 
from myservice.telemetry import setup_telemetry
 
# Before Flask and psycopg are imported, in each gunicorn worker.
setup_telemetry()
 
logging.basicConfig(
    level=os.getenv("LOG_LEVEL", "INFO").upper(),
    format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
)
 
from myservice.app import create_app  # noqa: E402
 
app = create_app()
# 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
accesslog = "-"
 
 
def worker_exit(server, worker):
    from sophonz.opentelemetry import shutdown
 
    shutdown()
export SOPHONZ_API_KEY=sk_...
export DATABASE_URL=postgresql://app:app@localhost:5432/app
export OTEL_METRICS_EXPORTER=none
 
gunicorn -c gunicorn.conf.py myservice.wsgi:app

On macOS, also set OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES for gunicorn.

Trying it

With any of the servers running on port 8000:

curl -s -X POST localhost:8000/api/users \
  -H "content-type: application/json" \
  -d '{"email": "ada@example.com", "name": "Ada"}'
 
curl -s localhost:8000/api/users/1 \
  -H "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" \
  -H "baggage: session.id=test-session-1"
 
curl -s localhost:8000/api/error

What you get

For the second request, which carries the headers a browser instrumented with the Sophonz Browser SDK would send:

  • a server span in trace 4bf92f3577b34da6a3ce929d0e0e4736 whose parent is span 00f067aa0ba902b7;
  • session.id, baggage.session.id, http.client.ip, and http.user_agent on the server span and every child span;
  • a psycopg client span per query, and in the PostgreSQL log each statement ending with /*traceparent='00-4bf92f3577b34da6a3ce929d0e0e4736-...'*/, which pg_tracing turns into database spans in the same trace;
  • request and response headers on the server span, with authorization and cookie values redacted.

For the other requests:

  • logging records exported with the trace and span IDs of the request, with count or user_id as attributes;
  • for /api/error, an ERROR server span with one exception event and one error log record;
  • for a second POST with the same email, a 409 response and an ERROR INSERT span with its own error log record, because the database raised.

Checking locally

Set SOPHONZ_DEBUG_PAYLOAD=true to print every exported span and log record to the console as well:

SOPHONZ_DEBUG_PAYLOAD=true gunicorn -c gunicorn.conf.py myservice.wsgi:app

If nothing is printed, check SOPHONZ_API_KEY first: without a key the SDK does not start and logs OpenTelemetry SDK initialization skipped. If spans print but do not appear in Sophonz, check that the key is a registered app key and that OTEL_EXPORTER_OTLP_ENDPOINT points at the collector.

Zero-code alternative

The Flask and FastAPI servers also run through opentelemetry-instrument with environment variables instead. Remove the setup_telemetry() call from the entrypoint, so the SDK is not started twice, and keep the helper calls in create_app(); they work however the SDK was started.

export SOPHONZ_API_KEY=sk_...
export OTEL_SERVICE_NAME=example-flask
export OTEL_METRICS_EXPORTER=none
export SOPHONZ_PYTHON_EXPERIMENTAL_EXCEPTION_CAPTURE=true
export SOPHONZ_PYTHON_ADVANCED_NETWORK_CAPTURE=true
export SOPHONZ_PYTHON_INSTRUMENTATIONS='{"psycopg": {"enable_commenter": true, "commenter_options": {"db_driver": false, "dbapi_threadsafety": false, "dbapi_level": false, "libpq_version": false, "driver_paramstyle": false}}, "flask": {"enable_commenter": false}}'
 
opentelemetry-instrument gunicorn -c gunicorn.conf.py myservice.wsgi:app

See Deployment for how the two modes differ, and the Framework Guides for why each file is arranged the way it is.

TIP — This is just the beginning

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