Instrumentation

What the Sophonz Python SDK captures automatically and how to control it — instrumentation loading, logging and exception capture, advanced network capture with redaction, baggage promotion, and custom spans.

The SDK does not ship instrumentation of its own for frameworks, HTTP clients, or databases. It loads the official OpenTelemetry instrumentation packages that are installed, configures them, and adds what they lack: baggage and request attributes on every span, logging export, exception capture, body capture with redaction, and error logs for failed spans.

How instrumentations load

init() and opentelemetry-instrument both look up every package registered under the opentelemetry_instrumentor entry point and call its instrument(). Installing a package is what turns an instrumentation on.

ExtraInstrumentationProduces
flaskflaskServer spans for Flask routes
fastapifastapiServer spans, plus http receive / http send child spans
djangodjangoServer spans for Django views
requestsrequestsClient spans; injects traceparent and baggage into outgoing requests
httpxhttpxClient spans, sync and async; injects traceparent and baggage
psycopgpsycopgA client span per query for psycopg 3
psycopg2psycopg2A client span per query for psycopg2
sqlalchemysqlalchemyA client span per query for engines created after init()
loggingloggingLog correlation fields on LogRecords (the SDK exports logs without it)

The extras are the instrumentations this SDK is tested with. opentelemetry-bootstrap -a install installs an instrumentation for every supported library it finds in the environment, and those load too.

An instrumentation is skipped, with a debug log, when:

  • the library it instruments is not installed, or its version is outside the range the instrumentation supports;
  • it was already instrumented in this process;
  • it is disabled by configuration (below).

To see the outcome for each one, set SOPHONZ_DEBUG=true and configure a log handler before init() runs, for example with logging.basicConfig(). The SDK then logs Instrumented <name> or Skipping instrumentation <name>: <reason> at startup.

Configuring and disabling

The instrumentations option maps an instrumentation name to the keyword arguments passed to its instrument(). {"enabled": False} skips it.

init(
    service="checkout-api",
    instrumentations={
        "psycopg": {"enable_commenter": True},
        "fastapi": {"exclude_spans": ["receive", "send"]},
        "urllib3": {"enabled": False},
    },
)
  • Keys are entry point names. The package name (opentelemetry-instrumentation-psycopg) and module name (opentelemetry.instrumentation.psycopg) are accepted too.
  • The accepted arguments are those of the upstream instrumentation.
  • For one instrumentation, later sources win: advanced network capture hooks, then SOPHONZ_PYTHON_SQLCOMMENTER, then your instrumentations entry.

Under opentelemetry-instrument, pass the same map as JSON:

export SOPHONZ_PYTHON_INSTRUMENTATIONS='{"psycopg": {"enable_commenter": true}, "urllib3": {"enabled": false}}'

OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=requests,urllib3 skips instrumentations by name in both modes; * skips all of them.

An instrumentor that is not registered as an entry point can be passed as an instance. The SDK calls its instrument() with no arguments after the installed ones:

from myteam.telemetry import CacheInstrumentor
 
init(service="checkout-api", additional_instrumentations=[CacheInstrumentor()])

The SDK's own export requests

The SDK adds its 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 values you already set there or in OTEL_PYTHON_EXCLUDED_URLS. Exports never show up as outgoing HTTP spans.

Logs

With console_capture (on by default), the SDK attaches an OTLP handler to the root logger.

  • Records are exported at the level your logging configuration lets through the root logger. Python's default is WARNING; set INFO to export info logs.
  • A record emitted inside a span carries that span's trace and span IDs.
  • extra={...} fields become log attributes.
  • print() and direct writes to stdout are not captured.
import logging
 
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("checkout")
 
logger.info("order placed", extra={"order_id": 42})

logging.basicConfig, logging.config.dictConfig (including Django's LOGGING), and logging.config.fileConfig can run before or after init(); the OTLP handler stays on the root logger either way.

When opentelemetry-instrumentation-logging is installed, the SDK sets OTEL_PYTHON_LOG_AUTO_INSTRUMENTATION=false unless you set it, so records are not exported twice.

Exceptions

Exceptions reach the trace in three ways, and each is recorded once.

SourceRecorded byexception.mechanism
Exception escaping a Flask, FastAPI, or Django routeThe framework instrumentation; the SDK's error handler records it only when no instrumentation didflask, asgi, django, when the error handler is registered
Uncaught exception in the main threadsys.excepthooksys.excepthook
Uncaught exception in another threadthreading.excepthookthreading.excepthook
Exception reported to the asyncio loop's exception handlerLoop exception handler hookasyncio
Your own callrecord_exception()generic, or the mechanism you pass

The three hooks are installed by experimental_exception_capture, which init() turns on. After recording from sys.excepthook or threading.excepthook, the SDK flushes, because the process may be about to exit, and then calls the hook that was installed before. KeyboardInterrupt in the main thread and SystemExit in other threads are ignored. The asyncio hook covers the standard event loop only.

record_exception() records a handled exception as an exception event and sets the span status to ERROR:

from sophonz.opentelemetry import record_exception
 
try:
    charge(order)
except PaymentDeclined as exc:
    record_exception(exc, attributes={"order.id": order.id})
    raise

It records on span= when given, otherwise on the current span. With no span in context it starts and ends a span named after the exception type, so the exception is not lost.

Error logs for failed spans

With error_log_capture (on by default), every span that ends with ERROR status and an exception event or status description also emits one log record, linked to the span's trace:

AttributeValue
app.span.typeerror
exception.typeException class name
exception.messageMessage, cut at 1024 characters
exception.stacktraceStack trace, cut at 4096 characters
trace.id, span.id, span.nameThe failed span

The record's body is the stack trace. The shape matches the Node.js and browser SDKs, so errors from every tier can be queried the same way. The record is produced even when console_capture is off, and not when logs are disabled.

Advanced network capture

advanced_network_capture=True, or SOPHONZ_PYTHON_ADVANCED_NETWORK_CAPTURE=true, adds HTTP headers and bodies to spans.

Headers

The SDK sets these variables, unless you set them yourself:

VariableValue
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST.*
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE.*
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST.*
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE.*
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDSauthorization,proxy-authorization,cookie,set-cookie,x-api-key

The instrumentations record headers as http.request.header.<name> and http.response.header.<name>, lowercased with - replaced by _ (http.request.header.user_agent). On requests and urllib client spans, the SDK's hooks also record each header under its original name (http.request.header.user-agent).

Values of authorization, proxy-authorization, cookie, set-cookie, and x-api-key are recorded as [REDACTED]. To redact more, set the sanitize variable yourself and include these five; a value you set replaces the default list.

export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS="authorization,proxy-authorization,cookie,set-cookie,x-api-key,x-session-token"

To capture fewer headers, set the capture variables to a comma-separated list of names or regular expressions instead of .*.

Bodies

InstrumentationRequest bodyResponse body
requestsYesOnly when the response was read (not with stream=True before the body is consumed)
urllibYesNo; reading it would consume the stream before your code does
fastapi, starletteYes, on the http receive spanYes, on the http send span
flask, django, httpxNoNo

Bodies are recorded as http.request.body and http.response.body. For FastAPI, excluding the receive and send spans with exclude_spans also stops body capture.

Redaction rules

  • Bodies are cut to 16 KiB (16,384 bytes) and decoded as UTF-8.

  • If the body contains any of these keywords, case-insensitively and anywhere in the text, the whole body is replaced with [Filtered]:

    password, passwd, secret, api_key, apikey, auth, credentials, mysql_pwd, privatekey, private_key, token, session, csrftoken, sessionid, x_csrftoken, set_cookie, cookie, authorization, x_api_key, aiohttp_session, connect.sid, csrf_token, csrf, _csrf, _csrf_token, phpsessid, _session, symfony, user_session, _xsrf, xsrf-token

  • The match is a substring match, so ordinary field names can trigger it: {"authorId": 1} contains auth and is recorded as [Filtered].

  • The list is the same as the Node.js SDK's and cannot be changed.

WARNING — Bodies can still contain personal data

Redaction only looks for credential-like keywords. Names, email addresses, and other personal data pass through. Enable body capture only where storing request and response content is acceptable.

Baggage and session.id

For every span it starts, the SDK copies each W3C baggage entry in the span's context onto the span as baggage.<key>. This happens in the span processor, so server spans, database spans, HTTP client spans, and your own spans all get them.

Keys listed in promote_baggage_keys are also copied under their own name. The default is ["session.id"]: the Sophonz browser SDK sends the session ID in the baggage header, and every server span of that request carries both baggage.session.id and session.id.

init(service="checkout-api", promote_baggage_keys=["session.id", "tenant.id"])

Passing a list replaces the default, so include session.id when you add keys.

Baggage you set in Python is copied onto spans started under it and sent to downstream services by the requests and httpx instrumentations:

from sophonz.opentelemetry import baggage, context
 
token = context.attach(baggage.set_baggage("tenant.id", "acme"))
try:
    sync_tenant()  # spans here carry baggage.tenant.id
finally:
    context.detach(token)

CAUTION — Baggage leaves your service

Every outgoing request made with an instrumented HTTP client carries the baggage header, including requests to third parties. Do not put secrets or personal data in baggage.

Custom spans

sophonz.opentelemetry re-exports the OpenTelemetry API, so custom spans need no extra import. Spans you start inside a request are children of the request span and are exported with it.

from sophonz.opentelemetry import SpanKind, Status, StatusCode, trace
 
tracer = trace.get_tracer("checkout")
 
 
def price_cart(cart):
    with tracer.start_as_current_span("price-cart", attributes={"cart.size": len(cart.items)}) as span:
        total = sum(item.price for item in cart.items)
        span.set_attribute("cart.total", total)
        if total <= 0:
            span.set_status(Status(StatusCode.ERROR, "empty cart"))
        return total
 
 
def call_tax_service(order):
    with tracer.start_as_current_span("tax.calculate", kind=SpanKind.CLIENT):
        ...

Attributes for the whole request

span.set_attribute() changes one span. set_trace_attributes() sets attributes on every span of the current request in this process: the server span, spans already open, and every span started later under the same local root. An attribute a span already has is not overwritten.

from sophonz.opentelemetry import set_trace_attributes
 
 
@app.get("/api/orders/<order_id>")
def get_order(order_id):
    user = current_user()
    set_trace_attributes({"enduser.id": user.id, "tenant.id": user.tenant_id})
    return load_order(order_id)  # database spans carry enduser.id and tenant.id

The local root is the first span started in this process for the request, so an upstream service's spans are not changed. Outside a span, the call does nothing. This is what the framework helpers use for their request attributes.

Metrics

The meter provider is set up too, and the OpenTelemetry metrics API works as usual:

from sophonz.opentelemetry import metrics
 
orders = metrics.get_meter("checkout").create_counter("orders.placed")
orders.add(1, {"payment.method": "card"})

NOTE — Metrics at the hosted endpoint

https://in.sophonz.ai currently accepts traces and logs. Its /v1/metrics path answers 404, and the metrics exporter logs an export error every interval. When exporting there, set OTEL_METRICS_EXPORTER=none or disable_metrics=True. See Deployment.

Next steps

TIP — This is just the beginning

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