Installation

Install and initialize the Sophonz Python SDK — programmatically with init() or with the opentelemetry-instrument command — and shut it down cleanly under gunicorn and uvicorn.

Install sophonz-opentelemetry with the extras for your framework and database, then call init() before the rest of your application loads. If you prefer no code changes, start your app through opentelemetry-instrument instead.

Quick start

Enter the collector URL, project, app name, version and app key below and pick a tab (Plain Python · Flask · FastAPI) to generate the initialization code from those values. Advanced options are behind the "Advanced options" toggle.

# instrument.py — import before the rest of your app
from sophonz.opentelemetry import init

init(
    service="next-sample",
    service_version="1.0.0",
    service_namespace="sophonz",
    api_key="sk_tYtJUa4WweXXedj6lxjSqoPW5O0DnbXz",
    endpoint="https://in.sophonz.ai",
)

Install

pip install "sophonz-opentelemetry[flask,psycopg]"
# or
uv add "sophonz-opentelemetry[fastapi,psycopg]"
# or
poetry add "sophonz-opentelemetry[django,psycopg]"

Each extra installs the matching OpenTelemetry instrumentation:

ExtraInstalls
flaskopentelemetry-instrumentation-flask
fastapiopentelemetry-instrumentation-fastapi
djangoopentelemetry-instrumentation-django
psycopgopentelemetry-instrumentation-psycopg (psycopg 3)
psycopg2opentelemetry-instrumentation-psycopg2
sqlalchemyopentelemetry-instrumentation-sqlalchemy
requestsopentelemetry-instrumentation-requests
httpxopentelemetry-instrumentation-httpx
loggingopentelemetry-instrumentation-logging
grpcopentelemetry-exporter-otlp-proto-grpc, for OTEL_EXPORTER_OTLP_PROTOCOL=grpc

To install instrumentations for every library detected in your environment instead, run:

opentelemetry-bootstrap -a install

TIP — Get your API key

Log in to the Sophonz console, register an app, and copy the issued key (sk_...). Provide it as the api_key argument or the SOPHONZ_API_KEY environment variable. Without an API key (and no OTEL_EXPORTER_OTLP_HEADERS), the SDK logs a warning and skips initialization.

Programmatic initialization

Call init() as early as possible — before Flask, FastAPI, Django, or database clients are imported. The Framework Guides show the exact place for each framework.

# instrument.py
import os
 
from sophonz.opentelemetry import init
 
init(
    service="my-app",
    api_key=os.getenv("SOPHONZ_API_KEY"),
)
# app.py
import instrument  # noqa: F401  (must come first)
 
from flask import Flask
 
app = Flask(__name__)

init() loads every installed OpenTelemetry instrumentation and turns on Sophonz's recommended defaults: console (logging) capture and exception capture. To take explicit control of every option, use init_sdk() instead — see Configuration.

init() returns True when the SDK started and False when it was skipped (no key) or already running. Call it once per process; OpenTelemetry allows the global providers to be set only once.

NOTE — Django

The Django instrumentation reads your settings when it is loaded, so set DJANGO_SETTINGS_MODULE before calling init() in manage.py, wsgi.py, or asgi.py. See the examples.

opentelemetry-instrument (zero-code)

Configure the SDK with environment variables and prefix your start command:

export SOPHONZ_API_KEY=sk_...
export OTEL_SERVICE_NAME=my-service
 
opentelemetry-instrument python app.py
opentelemetry-instrument flask run
opentelemetry-instrument uvicorn main:app
opentelemetry-instrument gunicorn app:app

opentelemetry-instrument finds the Sophonz distro through its package entry point, starts the SDK, and then loads every installed instrumentation with the configuration from SOPHONZ_PYTHON_INSTRUMENTATIONS and SOPHONZ_PYTHON_SQLCOMMENTER. Do not also call init() in the same process.

The distro applies the init_sdk() defaults, not init()'s: uncaught exception capture is off unless you set SOPHONZ_PYTHON_EXPERIMENTAL_EXCEPTION_CAPTURE=true.

NOTE — Another distro installed?

If opentelemetry-distro or another distro is installed in the same environment, set OTEL_PYTHON_DISTRO=sophonz so the Sophonz distro is the one selected.

Graceful shutdown

By default (stop_on_termination_signals=True) the SDK installs SIGTERM and SIGINT handlers that flush buffered telemetry and then hand the signal to the handler that was there before: a server's own graceful shutdown keeps working, and a process with no handler terminates as it would have. The providers also flush when the interpreter exits normally.

To manage shutdown yourself, pass stop_on_termination_signals=False and call shutdown():

import atexit
 
from sophonz.opentelemetry import init, shutdown
 
init(service="my-app", stop_on_termination_signals=False)
atexit.register(shutdown)

uvicorn

uvicorn main:app installs its own signal handlers before it imports your app, so the SDK's handler flushes and then calls uvicorn's graceful shutdown. When uvicorn has drained requests it restores the default handlers and re-sends the signal, which ends the process without running exit hooks. sophonz_fastapi_middleware therefore flushes again when the application finishes its lifespan shutdown, so spans from the drain are exported. For an ASGI app without that middleware (Django under uvicorn, for example), spans that end during the drain can miss the final export; lower OTEL_BSP_SCHEDULE_DELAY or call force_flush() from your own shutdown code. Run without --reload so the SDK is not started in a reloader process.

gunicorn

Without --preload, each worker imports your app after installing its own signal handlers, so the SDK's handler flushes and then calls gunicorn's; the worker then exits normally and the providers flush again at exit. With --preload, the app (and init()) runs in the master before workers are forked, and gunicorn then replaces the SDK's handlers in the master and in each worker. Telemetry still works in the workers — the batch processors restart their export threads after fork — and is flushed when a worker exits. To make the flush explicit, add a worker_exit hook:

# gunicorn.conf.py
from sophonz.opentelemetry import shutdown
 
 
def worker_exit(server, worker):
    shutdown()

If you prefer each worker to start its own SDK under --preload, do not call init() at import time; call it from post_fork instead (gunicorn installs its worker signal handlers after post_fork, so rely on worker_exit for the flush):

# gunicorn.conf.py
import os
 
from sophonz.opentelemetry import init, shutdown
 
preload_app = True
 
 
def post_fork(server, worker):
    init(service="my-app", api_key=os.getenv("SOPHONZ_API_KEY"))
 
 
def worker_exit(server, worker):
    shutdown()

CAUTION — macOS and fork

On macOS, a forked worker that exports over HTTPS can be aborted by the Objective-C runtime. Set OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES when running gunicorn locally on macOS. Linux is not affected.

Next steps

  • Configuration — every init() option and environment variable.
  • Framework Guides — Flask, FastAPI, and Django wiring with gunicorn and uvicorn.
  • Deployment — containers, Kubernetes, and graceful shutdown.
  • Examples — complete Flask, FastAPI, and Django servers.

TIP — This is just the beginning

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