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_sdk
  • init(**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

OptionTypeDefaultEnvironment variableDescription
servicestrunknown_service:pythonOTEL_SERVICE_NAMEService name (service.name).
api_keystr—SOPHONZ_API_KEYAPI key. Sent as the authorization header and the service.key resource attribute.
service_versionstr—OTEL_SERVICE_VERSIONservice.version.
service_namespacestr—SOPHONZ_SERVICE_NAMESPACEservice.namespace. OTEL_RESOURCE_ATTRIBUTES=service.namespace=... also works.
deployment_environmentstr—SOPHONZ_DEPLOYMENT_ENVIRONMENTdeployment.environment.name.

Capture toggles

OptionTypeDefaultEnvironment variableDescription
console_captureboolTrueSOPHONZ_PYTHON_CONSOLE_CAPTUREExport standard library logging records. See Logs.
experimental_exception_captureboolFalse*SOPHONZ_PYTHON_EXPERIMENTAL_EXCEPTION_CAPTURERecord uncaught exceptions from sys.excepthook, threading.excepthook, and asyncio event loops.
error_log_captureboolTrueSOPHONZ_PYTHON_ERROR_LOG_CAPTUREEmit an error log record for every span that ends with an ERROR status.
advanced_network_captureboolFalseSOPHONZ_PYTHON_ADVANCED_NETWORK_CAPTURECapture HTTP headers and bodies. See Advanced network capture.
beta_modeboolFalseSOPHONZ_PYTHON_BETA_MODEAccepted 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

OptionTypeDefaultEnvironment variableDescription
disable_tracingboolFalseOTEL_TRACES_EXPORTER=noneDo not set up tracing.
disable_logsboolFalseOTEL_LOGS_EXPORTER=noneDo not set up log export.
disable_metricsboolFalseOTEL_METRICS_EXPORTER=noneDo not set up metrics. https://in.sophonz.ai does not accept metrics yet; see Deployment.
detect_resourcesboolTrueSOPHONZ_PYTHON_DETECT_RESOURCESAdd process, OS, and host resource attributes.

Lifecycle and diagnostics

OptionTypeDefaultEnvironment variableDescription
stop_on_termination_signalsboolTrueSOPHONZ_PYTHON_STOP_ON_TERMINATION_SIGNALSFlush on SIGTERM / SIGINT, then run the previous handler. See Graceful shutdown.
disable_startup_logsboolFalseSOPHONZ_STARTUP_LOGS=falseSuppress the startup summary printed to stderr.
debugboolFalseSOPHONZ_DEBUGSet the SDK's own loggers (opentelemetry, sophonz) to DEBUG. Overrides log_level.
debug_payloadboolFalseSOPHONZ_DEBUG_PAYLOADAlso print every exported span, metric, and log record to stdout.
log_levelstr—OTEL_LOG_LEVELLevel for the SDK's own loggers: NOTSET, DEBUG, INFO, WARNING, ERROR, or CRITICAL. The root logger is never changed.

Advanced and extension

OptionTypeDefaultEnvironment variableDescription
instrumentationsdict[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_instrumentationslist[]—Instrumentor instances to instrument() after the installed ones.
promote_baggage_keyslist[str]["session.id"]—Baggage keys also copied under their own attribute name. A list replaces the default.
excluded_pathslist[str][]SOPHONZ_EXCLUDED_PATHS (comma-separated)Request paths that get no server span, for periodic requests such as health checks. See Excluded paths.
samplerSampler—OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARGA sampler instance. When not given, the sampler named by OTEL_TRACES_SAMPLER is used, parentbased_always_on by default.

Export

OptionTypeDefaultEnvironment variableDescription
endpointstrhttps://in.sophonz.aiOTEL_EXPORTER_OTLP_ENDPOINTBase collector URL. With http/protobuf, /v1/traces, /v1/metrics, and /v1/logs are appended.
traces_endpoint, metrics_endpoint, logs_endpointstrbase + /v1/<signal>OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINTFull per-signal endpoint, used as-is.
exporter_protocolstrhttp/protobufOTEL_EXPORTER_OTLP_PROTOCOLhttp/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_protocolstrexporter_protocolOTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_PROTOCOLProtocol for one signal.
endpoint_insecureboolFalseOTEL_EXPORTER_OTLP_INSECUREgRPC only: connect without TLS.
traces_endpoint_insecure, metrics_endpoint_insecure, logs_endpoint_insecureboolendpoint_insecureOTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_INSECUREgRPC 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:

AttributeSource
service.keyapi_key / SOPHONZ_API_KEY
service.nameservice / OTEL_SERVICE_NAME
service.versionservice_version / OTEL_SERVICE_VERSION
service.namespaceservice_namespace / SOPHONZ_SERVICE_NAMESPACE
deployment.environment.namedeployment_environment / SOPHONZ_DEPLOYMENT_ENVIRONMENT
telemetry.distro.name, telemetry.distro.versionsophonz and the package version
process.runtime.name, process.runtime.versionThe 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_URLS you 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

VariableDefaultDescription
SOPHONZ_API_KEY—API key (authorization and service.key).
SOPHONZ_SERVICE_NAMESPACE—service.namespace.
SOPHONZ_DEPLOYMENT_ENVIRONMENT—deployment.environment.name.
SOPHONZ_PYTHON_CONSOLE_CAPTUREtrueExport logging records.
SOPHONZ_PYTHON_EXPERIMENTAL_EXCEPTION_CAPTUREfalseRecord uncaught exceptions.
SOPHONZ_PYTHON_ERROR_LOG_CAPTUREtrueError log record for failed spans.
SOPHONZ_PYTHON_ADVANCED_NETWORK_CAPTUREfalseCapture HTTP headers and bodies.
SOPHONZ_PYTHON_STOP_ON_TERMINATION_SIGNALStrueFlush on SIGTERM / SIGINT.
SOPHONZ_PYTHON_BETA_MODEfalseReserved for parity with the Node.js SDK.
SOPHONZ_PYTHON_DETECT_RESOURCEStrueProcess, OS, and host resource attributes.
SOPHONZ_PYTHON_INSTRUMENTATIONS—JSON map of per-instrumentation config.
SOPHONZ_PYTHON_SQLCOMMENTERfalseSQLCommenter on psycopg and psycopg2.
SOPHONZ_EXCLUDED_PATHS—Paths that get no server span (comma-separated).
SOPHONZ_STARTUP_LOGStruePrint the startup summary.
SOPHONZ_DEBUGfalseSDK loggers at DEBUG.
SOPHONZ_DEBUG_PAYLOADfalsePrint exported telemetry to stdout.

OpenTelemetry

VariableDefaultDescription
OTEL_SERVICE_NAMEunknown_service:pythonService name.
OTEL_SERVICE_VERSION—Service version.
OTEL_RESOURCE_ATTRIBUTES—Extra resource attributes.
OTEL_EXPORTER_OTLP_ENDPOINThttps://in.sophonz.aiBase OTLP endpoint.
OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINTbase + /v1/<signal>Per-signal endpoint.
OTEL_EXPORTER_OTLP_PROTOCOLhttp/protobufhttp/protobuf or grpc.
OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_PROTOCOLOTEL_EXPORTER_OTLP_PROTOCOLPer-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_INSECUREfalsegRPC without TLS.
OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_INSECUREOTEL_EXPORTER_OTLP_INSECUREPer-signal gRPC TLS setting.
OTEL_TRACES_SAMPLER / OTEL_TRACES_SAMPLER_ARGparentbased_always_onTrace sampler.
OTEL_PROPAGATORStracecontext,baggageContext 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 captureHeader capture and redaction lists. See Instrumentation.
OTEL_PYTHON_LOG_AUTO_INSTRUMENTATIONfalse when console capture is onKeeps opentelemetry-instrumentation-logging from exporting records a second time.
OTEL_BSP_SCHEDULE_DELAY5000Span export interval in milliseconds.
OTEL_METRIC_EXPORT_INTERVAL60000Metric 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.