API Reference
Public API of the Sophonz Python SDK — init, init_sdk, shutdown, force_flush, trace attributes, exception recording, SophonzOptions, the Flask, FastAPI, and Django helpers, and the re-exported OpenTelemetry API.
The core API is exported from sophonz.opentelemetry. Framework helpers live in sophonz.opentelemetry.flask, sophonz.opentelemetry.fastapi, and sophonz.opentelemetry.django; each imports its framework only when used. Nothing in the API raises because of a telemetry failure.
Lifecycle
init(**options) -> bool
Recommended entry point. Applies the Sophonz defaults console_capture=True and experimental_exception_capture=True unless you pass them, then calls init_sdk() with everything else. Loads every installed instrumentation.
import os
from sophonz.opentelemetry import init
init(service="checkout-api", api_key=os.getenv("SOPHONZ_API_KEY"))Returns True when the SDK started. Returns False, after logging a warning, when no API key, OTEL_EXPORTER_OTLP_HEADERS, or service.key resource attribute is configured, or when the SDK is already running in this process.
init_sdk(**options) -> bool
init_sdk(
*,
service=None,
api_key=None,
console_capture=None,
experimental_exception_capture=None,
advanced_network_capture=None,
beta_mode=None,
disable_tracing=None,
disable_logs=None,
disable_metrics=None,
detect_resources=None,
stop_on_termination_signals=None,
disable_startup_logs=None,
instrumentations=None,
additional_instrumentations=None,
**options,
) -> boolStarts the SDK with only the per-option defaults: argument, then environment variable, then built-in default. None means not set. **options takes the remaining configuration options: service_version, service_namespace, deployment_environment, error_log_capture, promote_baggage_keys, sampler, the endpoint, protocol, and insecure options, debug, debug_payload, and log_level. All arguments are keyword-only. Same return value as init().
shutdown(timeout_millis: int = 5000) -> None
Flushes and shuts down the tracer, logger, and meter providers, restores the signal handlers and exception hooks the SDK replaced, and stops export. Telemetry recorded afterwards is dropped. Safe to call more than once and before init(). Use it in gunicorn's worker_exit and at the end of scripts.
force_flush(timeout_millis: int = 5000) -> bool
Exports everything buffered without shutting down. Returns False if a provider failed or timed out.
is_initialized() -> bool
Whether the SDK has been started in this process. A process forked after init() inherits True.
Trace attributes
set_trace_attributes(attributes: Mapping[str, AttributeValue]) -> None
Sets attributes on every span of the current request in this process: the spans already open under the same local root span (the server span included) and every span started under it afterwards. An attribute a span already has is not overwritten; None values are skipped. Outside a recording span it does nothing.
from sophonz.opentelemetry import set_trace_attributes
set_trace_attributes({"enduser.id": user.id, "tenant.id": user.tenant_id})Exceptions
record_exception(exc, attributes=None, span=None, mechanism="generic", escaped=False) -> None
| Parameter | Type | Description |
|---|---|---|
exc | BaseException | The exception to record. |
attributes | Mapping[str, AttributeValue] | None | Added to the exception event. |
span | Span | None | Span to record on. Defaults to the current span. |
mechanism | str | Stored as exception.mechanism on the event, unless attributes sets it. |
escaped | bool | Passed to OpenTelemetry's Span.record_exception. |
Adds an exception event and sets the span status to ERROR with the description <ExceptionType>: <message>. With no recording span, it starts and ends a span named after the exception type, with attributes as span attributes, so the exception is not lost. Never raises.
from sophonz.opentelemetry import record_exception
try:
sync_inventory()
except Exception as exc:
record_exception(exc, attributes={"job.name": "nightly-sync"})Debugging
enable_debug_payload_exporters() -> None
Adds console exporters to the running tracer and logger providers, so every span and log record exported after the call is also printed to stdout. Call it after init(). debug_payload=True or SOPHONZ_DEBUG_PAYLOAD=true does the same at startup and prints metrics as well.
from sophonz.opentelemetry import enable_debug_payload_exporters, init
init(service="checkout-api")
enable_debug_payload_exporters()Options object
SophonzOptions(**options)
The resolved configuration. Takes the same keyword-only arguments as init_sdk() and applies the same precedence. The SDK builds one internally; construct your own to inspect what a given environment resolves to:
from sophonz.opentelemetry import SophonzOptions
options = SophonzOptions(service="checkout-api")
print(options.has_identity(), options.get_traces_endpoint())| Member | Returns |
|---|---|
has_identity() | True when an API key, OTEL_EXPORTER_OTLP_HEADERS, or a service.key resource attribute is present. |
get_traces_endpoint(), get_metrics_endpoint(), get_logs_endpoint() | The resolved export URL for each signal. |
get_all_endpoints() | All three, as a list. |
get_trace_headers(), get_metrics_headers(), get_logs_headers() | Export headers: the OTEL_EXPORTER_OTLP_*_HEADERS values with the API key as authorization, or None. |
get_trace_endpoint_credentials(), get_metrics_endpoint_credentials(), get_logs_endpoint_credentials() | gRPC channel credentials, or None when insecure. Needs the grpc extra. |
apply_log_level() | Sets the opentelemetry and sophonz loggers to the resolved log_level. |
Every option is also available as an attribute with its resolved value (options.service, options.console_capture, options.instrumentations, and so on), plus options.sql_commenter for SOPHONZ_PYTHON_SQLCOMMENTER.
__version__
The package version, "0.1.0".
Flask
from sophonz.opentelemetry.flask import ... — requires the flask extra.
sophonz_flask_middleware(app, *, capture_baggage=True, capture_client_ip=True, capture_user_agent=True, attributes=None, instrument=True)
Registers a before_request hook that puts baggage.<key>, http.client.ip (from request.remote_addr), http.user_agent, and attributes on the server span and, through set_trace_attributes(), on every span of the request. attributes is a mapping or a function receiving the Flask request. With instrument=True, instruments the app with FlaskInstrumentor if it is not already, and logs a warning if the instrumentation is not installed. Returns app.
setup_flask_error_handler(app)
Connects to Flask's got_request_exception signal and records the exception on the request span. When the Flask instrumentation owns the span, which records the exception itself, only exception.mechanism=flask is added. Returns app.
FastAPI and Starlette
from sophonz.opentelemetry.fastapi import ... — requires the fastapi extra.
sophonz_fastapi_middleware(app, *, capture_baggage=True, capture_client_ip=True, capture_user_agent=True, attributes=None, instrument=True)
Appends SophonzASGIMiddleware as the innermost user middleware, so it runs inside the server span regardless of registration order. With instrument=True, instruments the app with FastAPIInstrumentor if it is not already. Must be called before the app starts serving; raises RuntimeError otherwise. Works on any Starlette application with instrument=False. Returns app.
setup_fastapi_error_handler(app)
Appends SophonzExceptionMiddleware as the innermost user middleware. Same timing rule as above. Returns app.
SophonzASGIMiddleware(app, capture_baggage=True, capture_client_ip=True, capture_user_agent=True, attributes=None)
Pure ASGI middleware. For http and websocket scopes, enriches spans like the Flask helper; the client address comes from scope["client"] and attributes functions receive the ASGI scope. For the lifespan scope, flushes telemetry once the application sends lifespan.shutdown.complete or lifespan.shutdown.failed.
SophonzExceptionMiddleware(app)
Pure ASGI middleware that records an exception escaping the application, then re-raises it. Exceptions handled into a response inside it, such as HTTPException, never reach it. When the FastAPI, Starlette, or ASGI instrumentation owns the span, only exception.mechanism=asgi is added.
NOTE — Adding the classes directly
app.add_middleware(SophonzASGIMiddleware) makes it the outermost middleware. If the server span is created by middleware added earlier, enrichment then runs before that span exists. Prefer the two helper functions, which append innermost.
Django
from sophonz.opentelemetry.django import ... — requires the django extra.
SophonzMiddleware
Django middleware for MIDDLEWARE, sync and async capable. Enriches spans like the Flask helper, using REMOTE_ADDR and HTTP_USER_AGENT. Its process_exception records view exceptions other than Http404, PermissionDenied, BadRequest, and SuspiciousOperation, and returns None so Django's handling continues.
Configured by the optional SOPHONZ_MIDDLEWARE setting, read once when the middleware is created:
SOPHONZ_MIDDLEWARE = {
"capture_baggage": True,
"capture_client_ip": True,
"capture_user_agent": True,
"attributes": "mysite.telemetry.request_attributes", # dict, callable, or dotted path
}instrument_django(**kwargs) -> None
Instruments Django with DjangoInstrumentor, passing kwargs to instrument(), unless it is already instrumented. init() does this when opentelemetry-instrumentation-django is installed; call it yourself only when the SDK was started without loading instrumentations. Call it after DJANGO_SETTINGS_MODULE is set.
Distro
sophonz.opentelemetry.distro.SophonzDistro
The distro opentelemetry-instrument loads, registered as sophonz under the opentelemetry_distro entry point. It starts the SDK from environment variables and applies the SOPHONZ_PYTHON_INSTRUMENTATIONS, SOPHONZ_PYTHON_SQLCOMMENTER, and advanced network capture settings to each instrumentation. Select it with OTEL_PYTHON_DISTRO=sophonz when more than one distro is installed.
OpenTelemetry API
sophonz.opentelemetry re-exports the OpenTelemetry API modules applications commonly need:
| Name | Is |
|---|---|
trace | opentelemetry.trace |
metrics | opentelemetry.metrics |
baggage | opentelemetry.baggage |
context | opentelemetry.context |
propagate | opentelemetry.propagate |
SpanKind, Status, StatusCode | From opentelemetry.trace |
from sophonz.opentelemetry import trace
tracer = trace.get_tracer("checkout")
with tracer.start_as_current_span("price-cart") as span:
span.set_attribute("cart.size", len(items))See Instrumentation for custom spans, baggage, and metrics.