Configuration
Full reference for Sophonz Python SDK configuration — init()/init_sdk() options, instrumentation config, SQLCommenter for PostgreSQL, and the SOPHONZ_* / OTEL_* environment variables.
The SDK is configured through keyword arguments to init() / init_sdk(), or through environment variables. Arguments always take precedence over environment variables; environment variables are the fallback, and the only way to configure the SDK under opentelemetry-instrument.
init() vs init_sdk()
from sophonz.opentelemetry import init, init_sdkinit(**options)— recommended entry point. Applies Sophonz defaults (console_capture=True,experimental_exception_capture=True) and your arguments on top.init_sdk(**options)— lower-level. Applies only the per-option defaults below (argument, then environment variable, then built-in default), with no opinionated toggles.
Both start the tracer, meter, and logger providers, set them as the OpenTelemetry globals, and load every installed OpenTelemetry instrumentation. Both return True when the SDK started, and False when it was skipped because no API key is configured or because it is already running.
Options
Core
| Option | Type | Default | Environment variable | Description |
|---|---|---|---|---|
service | str | unknown_service:python | OTEL_SERVICE_NAME | Service name (service.name). |
api_key | str | — | SOPHONZ_API_KEY | API key. Sent as the authorization header and the service.key resource attribute. |
service_version | str | — | OTEL_SERVICE_VERSION | service.version. |
service_namespace | str | — | SOPHONZ_SERVICE_NAMESPACE | service.namespace. OTEL_RESOURCE_ATTRIBUTES=service.namespace=... also works. |
deployment_environment | str | — | SOPHONZ_DEPLOYMENT_ENVIRONMENT | deployment.environment.name. |
Capture toggles
| Option | Type | Default | Environment variable | Description |
|---|---|---|---|---|
console_capture | bool | True | SOPHONZ_PYTHON_CONSOLE_CAPTURE | Export standard library logging records. See Logs. |
experimental_exception_capture | bool | False* | SOPHONZ_PYTHON_EXPERIMENTAL_EXCEPTION_CAPTURE | Record uncaught exceptions from sys.excepthook, threading.excepthook, and asyncio event loops. |
error_log_capture | bool | True | SOPHONZ_PYTHON_ERROR_LOG_CAPTURE | Emit an error log record for every span that ends with an ERROR status. |
advanced_network_capture | bool | False | SOPHONZ_PYTHON_ADVANCED_NETWORK_CAPTURE | Capture HTTP headers and bodies. See Advanced network capture. |
beta_mode | bool | False | SOPHONZ_PYTHON_BETA_MODE | Accepted for parity with the Node.js SDK. It currently changes nothing: trace attributes are always on. |
NOTE — * Defaults differ between init() and init_sdk()
experimental_exception_capture defaults to False in init_sdk(), but init() turns it on. console_capture is True in both.
Signal toggles
| Option | Type | Default | Environment variable | Description |
|---|---|---|---|---|
disable_tracing | bool | False | OTEL_TRACES_EXPORTER=none | Do not set up tracing. |
disable_logs | bool | False | OTEL_LOGS_EXPORTER=none | Do not set up log export. |
disable_metrics | bool | False | OTEL_METRICS_EXPORTER=none | Do not set up metrics. https://in.sophonz.ai does not accept metrics yet; see Deployment. |
detect_resources | bool | True | SOPHONZ_PYTHON_DETECT_RESOURCES | Add process, OS, and host resource attributes. |
Lifecycle and diagnostics
| Option | Type | Default | Environment variable | Description |
|---|---|---|---|---|
stop_on_termination_signals | bool | True | SOPHONZ_PYTHON_STOP_ON_TERMINATION_SIGNALS | Flush on SIGTERM / SIGINT, then run the previous handler. See Graceful shutdown. |
disable_startup_logs | bool | False | SOPHONZ_STARTUP_LOGS=false | Suppress the startup summary printed to stderr. |
debug | bool | False | SOPHONZ_DEBUG | Set the SDK's own loggers (opentelemetry, sophonz) to DEBUG. Overrides log_level. |
debug_payload | bool | False | SOPHONZ_DEBUG_PAYLOAD | Also print every exported span, metric, and log record to stdout. |
log_level | str | — | OTEL_LOG_LEVEL | Level for the SDK's own loggers: NOTSET, DEBUG, INFO, WARNING, ERROR, or CRITICAL. The root logger is never changed. |
Advanced and extension
| Option | Type | Default | Environment variable | Description |
|---|---|---|---|---|
instrumentations | dict[str, dict] | {} | SOPHONZ_PYTHON_INSTRUMENTATIONS (JSON) | Per-instrumentation instrument() arguments, or {"enabled": False} to skip one. An argument entry is merged over the environment entry for the same instrumentation. See Instrumentation. |
additional_instrumentations | list | [] | — | Instrumentor instances to instrument() after the installed ones. |
promote_baggage_keys | list[str] | ["session.id"] | — | Baggage keys also copied under their own attribute name. A list replaces the default. |
excluded_paths | list[str] | [] | SOPHONZ_EXCLUDED_PATHS (comma-separated) | Request paths that get no server span, for periodic requests such as health checks. See Excluded paths. |
sampler | Sampler | — | OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG | A sampler instance. When not given, the sampler named by OTEL_TRACES_SAMPLER is used, parentbased_always_on by default. |
Export
| Option | Type | Default | Environment variable | Description |
|---|---|---|---|---|
endpoint | str | https://in.sophonz.ai | OTEL_EXPORTER_OTLP_ENDPOINT | Base collector URL. With http/protobuf, /v1/traces, /v1/metrics, and /v1/logs are appended. |
traces_endpoint, metrics_endpoint, logs_endpoint | str | base + /v1/<signal> | OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT | Full per-signal endpoint, used as-is. |
exporter_protocol | str | http/protobuf | OTEL_EXPORTER_OTLP_PROTOCOL | http/protobuf or grpc (needs the grpc extra). An unknown value logs a warning and falls back to http/protobuf. |
traces_exporter_protocol, metrics_exporter_protocol, logs_exporter_protocol | str | exporter_protocol | OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_PROTOCOL | Protocol for one signal. |
endpoint_insecure | bool | False | OTEL_EXPORTER_OTLP_INSECURE | gRPC only: connect without TLS. |
traces_endpoint_insecure, metrics_endpoint_insecure, logs_endpoint_insecure | bool | endpoint_insecure | OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_INSECURE | gRPC only: TLS setting for one signal. |
Endpoint resolution, highest first: the per-signal argument, endpoint (with the signal path), the per-signal environment variable, OTEL_EXPORTER_OTLP_ENDPOINT (with the signal path), then the default. The signal path (/v1/traces, /v1/metrics, /v1/logs) is appended only for http/protobuf; gRPC endpoints are used as given.
init() and init_sdk() accept every option in these tables as a keyword argument. Passing None counts as not set, so the environment variable applies.
Boolean environment variables accept true/false, 1/0, yes/no, and on/off.
Example
import os
from sophonz.opentelemetry import init_sdk
init_sdk(
service="checkout-api",
api_key=os.getenv("SOPHONZ_API_KEY"),
service_version="2.4.1",
deployment_environment="production",
console_capture=True,
experimental_exception_capture=True,
advanced_network_capture=True,
instrumentations={
# disable a noisy instrumentation
"urllib3": {"enabled": False},
# carry the trace into PostgreSQL
"psycopg": {"enable_commenter": True},
},
)Instrumentations
init() loads every OpenTelemetry instrumentation installed in the environment, like opentelemetry-instrument does. The instrumentations map is keyed by the instrumentation's entry point name — flask, fastapi, django, psycopg, psycopg2, sqlalchemy, requests, httpx, and so on. The package name (opentelemetry-instrumentation-psycopg) is accepted too. Each value is passed as keyword arguments to that instrumentor's instrument(); "enabled": False skips it.
OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=requests,urllib3 also skips instrumentations, and * skips all of them. What each instrumentation records is listed in Instrumentation.
Under opentelemetry-instrument, the same map is read from SOPHONZ_PYTHON_INSTRUMENTATIONS as JSON:
export SOPHONZ_PYTHON_INSTRUMENTATIONS='{"psycopg": {"enable_commenter": true}, "urllib3": {"enabled": false}}'Database query tracing
Installing the psycopg, psycopg2, or sqlalchemy extra traces every query as a client span. Carrying the trace into PostgreSQL needs SQLCommenter, which is disabled by default:
init(
service="checkout-api",
api_key=os.getenv("SOPHONZ_API_KEY"),
instrumentations={"psycopg": {"enable_commenter": True}},
)SOPHONZ_PYTHON_SQLCOMMENTER=true enables it for psycopg and psycopg2, including under opentelemetry-instrument; an explicit instrumentations entry wins over it. Per-driver options, trimming the comment to traceparent, SQLAlchemy and the Django ORM, and prepared statements are covered in Database Tracing.
Service identity
Every signal shares one resource. The SDK adds these attributes when a value is available:
| Attribute | Source |
|---|---|
service.key | api_key / SOPHONZ_API_KEY |
service.name | service / OTEL_SERVICE_NAME |
service.version | service_version / OTEL_SERVICE_VERSION |
service.namespace | service_namespace / SOPHONZ_SERVICE_NAMESPACE |
deployment.environment.name | deployment_environment / SOPHONZ_DEPLOYMENT_ENVIRONMENT |
telemetry.distro.name, telemetry.distro.version | sophonz and the package version |
process.runtime.name, process.runtime.version | The Python implementation (cpython) and version |
OTEL_RESOURCE_ATTRIBUTES keeps working and supplies any attribute the SDK does not set:
export OTEL_RESOURCE_ATTRIBUTES="service.namespace=sophonz,team=payments"Headers from OTEL_EXPORTER_OTLP_HEADERS and the per-signal header variables are merged into the export headers. When an API key is configured, it replaces any authorization header from those variables.
CAUTION — Missing key
If there is no API key, no OTEL_EXPORTER_OTLP_HEADERS, and no service.key in OTEL_RESOURCE_ATTRIBUTES, the SDK logs a warning and skips initialization, like the Node.js SDK. The Sophonz collector would drop that telemetry anyway.
With neither service nor OTEL_SERVICE_NAME (nor service.name in OTEL_RESOURCE_ATTRIBUTES), the SDK starts but logs a warning, and telemetry is reported as unknown_service:python.
With detect_resources (on by default), process, OS, and host attributes are added underneath; the attributes above win over detected values.
Context propagation and sampling
The propagators are the OpenTelemetry defaults, tracecontext,baggage (OTEL_PROPAGATORS). An incoming traceparent is continued by the server span, and the default parentbased_always_on sampler keeps every trace the browser sampled.
Every baggage entry is copied onto every span as baggage.<key>. session.id, which the Sophonz browser SDK sends, is also copied as session.id, so browser and server spans can be queried by one attribute. Change the promoted keys with promote_baggage_keys. The browser side, CORS, and verification are covered in Browser to Backend Tracing.
Logs
With console_capture, the SDK attaches an OTLP handler to the root logger. Records are exported at whatever level your logging configuration lets through the root logger (Python's default is WARNING), records emitted inside a span carry its trace and span IDs, and extra={...} fields become attributes. print() is not captured. logging.basicConfig, dictConfig, and fileConfig keep working before and after init().
With error_log_capture, a span that ends with an ERROR status also produces one error log record linked to it. See Instrumentation for both.
Advanced network capture
advanced_network_capture=True (or SOPHONZ_PYTHON_ADVANCED_NETWORK_CAPTURE=true) captures request and response headers on server and client spans, with authorization, proxy-authorization, cookie, set-cookie, and x-api-key recorded as [REDACTED], and bodies for requests, urllib (request bodies only), and FastAPI/Starlette. Bodies are cut to 16 KiB and replaced with [Filtered] when they contain a sensitive keyword. Which spans get what, the variables it sets, and the full keyword list are in Instrumentation.
WARNING — Sensitive data
Bodies can still contain personal data. Enable this only where that is acceptable.
Excluded paths
A request to a path listed in excluded_paths gets no server span in Flask, Django, FastAPI, and Starlette. Use it to keep health checks that arrive every few seconds, such as Kubernetes probes, out of your traces. Available from 0.2.0.
from sophonz.opentelemetry import init
init(excluded_paths=["/health", "/ready"])To set it in your deployment, use the environment variable.
SOPHONZ_EXCLUDED_PATHS=/health,/ready- Each entry is an exact path. The leading slash is optional and the query string is ignored.
- The default is an empty list: no path is excluded.
- It is added to any
OTEL_PYTHON_<FRAMEWORK>_EXCLUDED_URLSyou already set. - With the Flask, FastAPI, or Django helper, spans the request would start (a readiness probe's database query) are left out too.
Excluded URLs
The SDK adds its own export URLs to OTEL_PYTHON_REQUESTS_EXCLUDED_URLS, OTEL_PYTHON_URLLIB_EXCLUDED_URLS, OTEL_PYTHON_URLLIB3_EXCLUDED_URLS, and OTEL_PYTHON_HTTPX_EXCLUDED_URLS, keeping any values you already set (including OTEL_PYTHON_EXCLUDED_URLS). This keeps exports from being recorded as outgoing HTTP spans.
Environment variables
Sophonz-specific
| Variable | Default | Description |
|---|---|---|
SOPHONZ_API_KEY | — | API key (authorization and service.key). |
SOPHONZ_SERVICE_NAMESPACE | — | service.namespace. |
SOPHONZ_DEPLOYMENT_ENVIRONMENT | — | deployment.environment.name. |
SOPHONZ_PYTHON_CONSOLE_CAPTURE | true | Export logging records. |
SOPHONZ_PYTHON_EXPERIMENTAL_EXCEPTION_CAPTURE | false | Record uncaught exceptions. |
SOPHONZ_PYTHON_ERROR_LOG_CAPTURE | true | Error log record for failed spans. |
SOPHONZ_PYTHON_ADVANCED_NETWORK_CAPTURE | false | Capture HTTP headers and bodies. |
SOPHONZ_PYTHON_STOP_ON_TERMINATION_SIGNALS | true | Flush on SIGTERM / SIGINT. |
SOPHONZ_PYTHON_BETA_MODE | false | Reserved for parity with the Node.js SDK. |
SOPHONZ_PYTHON_DETECT_RESOURCES | true | Process, OS, and host resource attributes. |
SOPHONZ_PYTHON_INSTRUMENTATIONS | — | JSON map of per-instrumentation config. |
SOPHONZ_PYTHON_SQLCOMMENTER | false | SQLCommenter on psycopg and psycopg2. |
SOPHONZ_EXCLUDED_PATHS | — | Paths that get no server span (comma-separated). |
SOPHONZ_STARTUP_LOGS | true | Print the startup summary. |
SOPHONZ_DEBUG | false | SDK loggers at DEBUG. |
SOPHONZ_DEBUG_PAYLOAD | false | Print exported telemetry to stdout. |
OpenTelemetry
| Variable | Default | Description |
|---|---|---|
OTEL_SERVICE_NAME | unknown_service:python | Service name. |
OTEL_SERVICE_VERSION | — | Service version. |
OTEL_RESOURCE_ATTRIBUTES | — | Extra resource attributes. |
OTEL_EXPORTER_OTLP_ENDPOINT | https://in.sophonz.ai | Base OTLP endpoint. |
OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT | base + /v1/<signal> | Per-signal endpoint. |
OTEL_EXPORTER_OTLP_PROTOCOL | http/protobuf | http/protobuf or grpc. |
OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_PROTOCOL | OTEL_EXPORTER_OTLP_PROTOCOL | Per-signal protocol. |
OTEL_EXPORTER_OTLP_HEADERS | — | Extra export headers (key=value,key2=value2). Also satisfies the key check. |
OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_HEADERS | — | Per-signal export headers, merged over OTEL_EXPORTER_OTLP_HEADERS. |
OTEL_EXPORTER_OTLP_INSECURE | false | gRPC without TLS. |
OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_INSECURE | OTEL_EXPORTER_OTLP_INSECURE | Per-signal gRPC TLS setting. |
OTEL_TRACES_SAMPLER / OTEL_TRACES_SAMPLER_ARG | parentbased_always_on | Trace sampler. |
OTEL_PROPAGATORS | tracecontext,baggage | Context propagators. |
OTEL_TRACES_EXPORTER / OTEL_METRICS_EXPORTER / OTEL_LOGS_EXPORTER | — | Set to none to disable a signal. |
OTEL_PYTHON_DISABLED_INSTRUMENTATIONS | — | Comma-separated instrumentations to skip, or *. |
OTEL_PYTHON_EXCLUDED_URLS | — | URL patterns the server and client instrumentations do not trace. The SDK's own export URLs are always excluded from HTTP clients. |
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_* | set by advanced network capture | Header capture and redaction lists. See Instrumentation. |
OTEL_PYTHON_LOG_AUTO_INSTRUMENTATION | false when console capture is on | Keeps opentelemetry-instrumentation-logging from exporting records a second time. |
OTEL_BSP_SCHEDULE_DELAY | 5000 | Span export interval in milliseconds. |
OTEL_METRIC_EXPORT_INTERVAL | 60000 | Metric export interval in milliseconds. |
OTEL_LOG_LEVEL | — | SDK logging level. |
OTEL_PYTHON_DISTRO | — | Set to sophonz if more than one distro is installed. |
TIP — Precedence
A disable_logs / disable_tracing / disable_metrics argument or the matching OTEL_*_EXPORTER=none both turn a signal off. When both are present, the argument wins — disable_tracing=False keeps tracing on even with OTEL_TRACES_EXPORTER=none.