Skip to content

API reference

Generated reference documentation for each package. The pages are rebuilt and published with this site from main.

Language Reference Generated by
TypeScript TypeScript API TypeDoc
Rust Rust API · docs.rs rustdoc
Go pkg.go.dev Go doc comments
Python below mkdocstrings
Java Java API Javadoc

Build them locally with make docs (per language: make -C <lang> docs).

Python

Grow Codes SDK for the OpenTelemetry Collector.

One-call OpenTelemetry bootstrap (traces, logs, metrics over OTLP), a health/version client and OTLP log exporters for the collector every Grow stack runs.

from grow_opentelemetry_collector import init_telemetry, OtelCollectorClient handle = init_telemetry() # doctest: +SKIP client = OtelCollectorClient.from_env() # doctest: +SKIP

AttrValue module-attribute

AttrValue: TypeAlias = str | int | float | bool | Sequence['AttrValue'] | Mapping[str, 'AttrValue']

Attribute value: scalar, list of values or nested mapping (OTel AnyValue without bytes).

AsyncBaseLogQueryClient

Async :class:BaseLogQueryClient.

AsyncBaseTraceQueryClient

Async :class:BaseTraceQueryClient.

query_trace_id

query_trace_id(trace_id: str) -> str

The id wait_for_trace passes to get_trace; override to keep native ids.

AsyncBatchProcessor

Bases: _BatchCore

Batches records for an :class:AsyncLogExporter on an asyncio task.

The task starts on the running loop at the first :meth:add (or :meth:flush). :meth:add may be called from other threads; it wakes the worker thread-safely. Exports are bounded by export_timeout_s with :func:asyncio.wait_for.

add

add(record: LogRecord) -> bool

Queue without blocking; False when dropped (block acts as drop_newest here).

add_wait async

add_wait(record: LogRecord) -> bool

Queue a record, waiting for queue space with drop_policy="block".

flush async

flush(timeout_s: float | timedelta | None = None) -> None

Export everything queued now; raises TimeoutError when timeout_s passes first.

shutdown async

shutdown(timeout_s: float | timedelta | None = None) -> None

Drain (bounded by timeout_s), stop the task, shut the exporter down; idempotent.

AsyncBatchingLogClient

Bases: _ClientBase

:class:AsyncLogClient over an :class:AsyncLogExporter + :class:AsyncBatchProcessor.

close async

close(timeout_s: float | timedelta | None = None) -> None

Flush and shut down; idempotent.

send_wait async

send_wait(record: LogRecord | LogInput) -> bool

Like :meth:send but waits for queue space with drop_policy="block".

AsyncCollectorHealthClient

Asynchronous :class:CollectorHealthClient; cancel a call by cancelling its task.

aclose async

aclose() -> None

Release connections (idempotent).

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> AsyncCollectorHealthClient

Build from the environment (see :meth:OtelCollectorConfig.from_env).

health async

health() -> HealthStatus

See :meth:CollectorHealthClient.health.

server_version async

server_version() -> str

See :meth:CollectorHealthClient.server_version.

wait_until_ready async

wait_until_ready(timeout_s: float | timedelta = DEFAULT_READY_TIMEOUT_S, *, interval_s: float | timedelta = DEFAULT_READY_INTERVAL_S) -> HealthStatus

See :meth:CollectorHealthClient.wait_until_ready.

AsyncCollectorLogQueryClient

Async LogQueryClient of the collector: every method raises :class:UnsupportedError.

list_labels async

list_labels() -> list[str]

Always :class:UnsupportedError.

list_streams async

list_streams() -> list[str]

Always :class:UnsupportedError.

search async

search(query: str, **_: Any) -> LogSearchResult

Always :class:UnsupportedError.

tail async

tail(query: str, on_record: Callable[[LogRecord], None], *, interval_s: float = 1.0) -> Any

Always :class:UnsupportedError.

wait_for_log async

wait_for_log(query: str, *, timeout_s: float | timedelta = 30.0, **_: Any) -> LogRecord

Always :class:UnsupportedError.

AsyncCollectorTraceQueryClient

Async TraceQueryClient of the collector: every method raises :class:UnsupportedError.

get_dependencies async

get_dependencies(*, start: datetime | None = None, end: datetime | None = None) -> list[DependencyLink]

Always :class:UnsupportedError.

get_trace async

get_trace(trace_id: str) -> Trace | None

Always :class:UnsupportedError.

list_operations async

list_operations(service: str) -> list[str]

Always :class:UnsupportedError.

list_services async

list_services() -> list[str]

Always :class:UnsupportedError.

search_traces async

search_traces(query: TraceSearchQuery | None = None) -> list[TraceSummary]

Always :class:UnsupportedError.

wait_for_trace async

wait_for_trace(trace_id: str, **_: Any) -> Trace

Always :class:UnsupportedError.

AsyncHttpTransport

Asynchronous transport (one per async client); options as for :class:HttpTransport.

Cancelling the calling task raises :class:CancelledError (an asyncio.CancelledError subclass) so asyncio's cancellation machinery keeps working. Every call after :meth:aclose raises :class:CancelledError ("client is closed").

aclose async

aclose() -> None

Close the connection pool and abort backoff sleeps (idempotent).

request async

request(req: Request) -> Response

Send req with retries; return the response or raise the mapped error.

AsyncLogClient

Bases: Protocol

Asynchronous log client: send stays synchronous, flush/close are awaited.

AsyncLogExporter

Bases: Protocol

Asynchronous exporter, awaited by :class:AsyncBatchProcessor on the caller's event loop.

AsyncLogQueryClient

Bases: Protocol

Asynchronous query API (same methods, awaited).

AsyncOtelCollectorClient

Bases: _ClientBase

Asynchronous OpenTelemetry Collector client; use async with or call :meth:aclose.

Cancel a call by cancelling its task: the SDK raises :class:CancelledError, which is also an :class:asyncio.CancelledError.

health_client property

health_client: AsyncCollectorHealthClient

The async health client.

aclose async

aclose() -> None

Flush and shut down everything this client created, then release connections. Idempotent. Blocking shutdowns (tracer/meter providers) run in a worker thread.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> AsyncOtelCollectorClient

See :meth:OtelCollectorClient.from_env.

health async

health() -> HealthStatus

See :meth:OtelCollectorClient.health.

init_telemetry

init_telemetry(**kwargs: Any) -> TelemetryHandle

:func:init_telemetry with this client's config; :meth:aclose shuts it down.

init_tracing

init_tracing(config: TracingConfig | None = None, **kwargs: Any) -> CollectorTracingHandle

:func:init_tracing with this client's config as defaults; :meth:aclose shuts it down.

log_client

log_client(**kwargs: Any) -> AsyncBatchingLogClient

An OTLP :class:AsyncBatchingLogClient (:func:create_async_log_client); call it inside a running event loop. :meth:aclose flushes and closes it.

log_exporter

log_exporter() -> AsyncOtlpLogExporter

A bare :class:AsyncOtlpLogExporter; :meth:aclose shuts it down.

log_query

log_query() -> AsyncCollectorLogQueryClient

Async log query client: every method raises :class:UnsupportedError.

ping async

ping() -> float

See :meth:OtelCollectorClient.ping.

request async

request(req: Request) -> Response

Send a raw request to the OTLP/HTTP receiver.

server_version async

server_version() -> str

See :meth:OtelCollectorClient.server_version.

trace_query

trace_query() -> AsyncCollectorTraceQueryClient

Async trace query client: every method raises :class:UnsupportedError.

wait_until_ready async

wait_until_ready(timeout_s: float | timedelta = DEFAULT_READY_TIMEOUT_S, *, interval_s: float | timedelta = DEFAULT_READY_INTERVAL_S) -> HealthStatus

See :meth:OtelCollectorClient.wait_until_ready.

AsyncOtlpLogExporter

Bases: _ExporterBase

Asynchronous :class:OtlpLogExporter (an AsyncLogExporter).

export async

export(records: Sequence[LogRecord], *, gzip: bool = True, timeout_s: float = 30.0) -> ExportResult

See :meth:OtlpLogExporter.export; task cancellation raises :class:CancelledError.

shutdown async

shutdown() -> None

Release connections; later exports fail with a ValidationError. Idempotent.

AsyncPollingTail

Async :class:PollingTail; the polling task runs on the current event loop.

AsyncTraceQueryClient

Bases: Protocol

Asynchronous trace query API (same methods, awaited).

AuthenticationError

Bases: OtelCollectorError

Credentials missing or rejected (HTTP 401).

BaseConfig dataclass

Common, immutable client settings. Durations are float seconds (timedelta accepted).

Service configs subclass this (@dataclass(frozen=True, repr=False)), override url with the service default, add their own fields (Secret for credentials), extend :meth:_env_values and :meth:validate, and list vendor variables in ENV_VENDOR.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> _C

Build from the environment, then validate.

Precedence: explicit keyword > GROW_OPENTELEMETRY_COLLECTOR_<NAME> > vendor variables > default. env defaults to os.environ; pass a dict in tests.

known_secrets

known_secrets() -> list[str]

Revealed values of every :class:Secret field (used to redact error text).

validate

validate() -> _C

Check the common rules; raise :class:ConfigError. Returns self.

BaseLogQueryClient

Base for service query clients: implement :meth:search, override what the service has.

tail defaults to :class:PollingTail; list_streams/list_labels raise UnsupportedError; wait_for_log uses :func:wait_for_log.

BaseTraceQueryClient

Base for service query clients; every method raises UnsupportedError until overridden (wait_for_trace uses :func:wait_for_trace on top of get_trace, passing the id through :meth:query_trace_id).

query_trace_id

query_trace_id(trace_id: str) -> str

The id wait_for_trace passes to get_trace; override to keep native ids.

BatchOptions dataclass

Batching options; durations are float seconds (timedelta accepted).

max_export_retries/retry_backoff_s: a batch whose export failed with a retryable SDK error (raised, or returned with nothing accepted) is exported again up to max_export_retries times, waiting retry_backoff_s * 2**n before retry n. Partial acceptance is final.

from_mapping classmethod

from_mapping(data: Mapping[str, Any]) -> BatchOptions

Build from the camelCase form used by conformance scenarios (flushIntervalMs …).

BatchProcessor

Bases: _BatchCore

Batches records for a synchronous :class:LogExporter on a daemon worker thread.

The worker starts with the first record. It exports when a batch is full, when flush_interval_s passed since the first queued record, on :meth:flush and on :meth:shutdown. Processors with a started worker are shut down at interpreter exit.

add

add(record: LogRecord) -> bool

Queue a record; False when it was dropped. Blocks only with drop_policy="block".

flush

flush(timeout_s: float | timedelta | None = None) -> None

Export everything queued now; raises TimeoutError when timeout_s passes first.

shutdown

shutdown(timeout_s: float | timedelta | None = None) -> None

Drain the queue (bounded by timeout_s), stop the worker and shut the exporter down.

Idempotent. Records still queued when the timeout passes are dropped with reason shutdown; later :meth:add calls are dropped the same way.

BatchStats dataclass

Counters of a batch processor (see the module docs for their meaning).

BatchingLogClient

Bases: _ClientBase

:class:LogClient over a synchronous :class:LogExporter and a :class:BatchProcessor.

redaction defaults to RedactionProcessor(); pass None to disable it. correlate adds the active span's ids to records without a trace id.

close

close(timeout_s: float | timedelta | None = None) -> None

Flush and shut down; idempotent.

CancelToken

Thread-safe cancellation flag passed to sync calls as cancel=.

Cancelling interrupts an in-flight request (the call returns immediately with :class:CancelledError; the abandoned HTTP exchange finishes in the background) and any retry backoff sleep.

cancel

cancel() -> None

Request cancellation (idempotent).

on_cancel

on_cancel(callback: Callable[[], None]) -> Callable[[], None]

Run callback on cancellation (now if already cancelled); returns an unregister.

wait

wait(timeout: float | None = None) -> bool

Block until cancelled or timeout; return whether the token is cancelled.

CancelledError

Bases: OtelCollectorError, CancelledError

The caller cancelled the operation (task cancel, :class:CancelToken, client close).

Also an :class:asyncio.CancelledError so asyncio keeps treating the task as cancelled.

CollectorHealthClient

Synchronous health client of an OpenTelemetry Collector.

health() reads the health_check extension (health_url) and, when that endpoint is unreachable (stock Grow stacks bind it to localhost), falls back to zpages {zpages_url}/debug/servicez. Every I/O method accepts cancel=.

close

close() -> None

Release connections (idempotent).

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> CollectorHealthClient

Build from the environment (see :meth:OtelCollectorConfig.from_env).

health

health(*, cancel: CancelToken | None = None) -> HealthStatus

Collector health; never raises for an unhealthy or unreachable collector.

200 {"status":"Server available",…} → healthy=True, status="ok" with details source="health_check", vendorStatus, upSince, uptime; 503 → unhealthy; unreachable → zpages fallback (details["source"] = "zpages"), else unreachable. Raises only :class:CancelledError and :class:ConfigError.

server_version

server_version(*, cancel: CancelToken | None = None) -> str

Collector version ("0.165.0"): zpages /debug/servicez Version row, else service_version of target_info at telemetry_url.

:class:UnsupportedError when neither answers with a version.

wait_until_ready

wait_until_ready(timeout_s: float | timedelta = DEFAULT_READY_TIMEOUT_S, *, interval_s: float | timedelta = DEFAULT_READY_INTERVAL_S, cancel: CancelToken | None = None) -> HealthStatus

Poll :meth:health until healthy and return that status.

Raises :class:TimeoutError after timeout_s and :class:CancelledError when cancel fires.

CollectorLogQueryClient

LogQueryClient of the collector: every method raises :class:UnsupportedError.

list_labels

list_labels() -> list[str]

Always :class:UnsupportedError.

list_streams

list_streams() -> list[str]

Always :class:UnsupportedError.

search

search(query: str, **_: Any) -> LogSearchResult

Always :class:UnsupportedError.

tail

tail(query: str, on_record: Callable[[LogRecord], None], *, interval_s: float = 1.0) -> Any

Always :class:UnsupportedError.

wait_for_log

wait_for_log(query: str, *, timeout_s: float | timedelta = 30.0, **_: Any) -> LogRecord

Always :class:UnsupportedError.

CollectorTraceQueryClient

TraceQueryClient of the collector: every method raises :class:UnsupportedError.

get_dependencies

get_dependencies(*, start: datetime | None = None, end: datetime | None = None) -> list[DependencyLink]

Always :class:UnsupportedError.

get_trace

get_trace(trace_id: str) -> Trace | None

Always :class:UnsupportedError.

list_operations

list_operations(service: str) -> list[str]

Always :class:UnsupportedError.

list_services

list_services() -> list[str]

Always :class:UnsupportedError.

search_traces

search_traces(query: TraceSearchQuery | None = None) -> list[TraceSummary]

Always :class:UnsupportedError.

wait_for_trace

wait_for_trace(trace_id: str, **_: Any) -> Trace

Always :class:UnsupportedError.

CollectorTracingHandle

Bases: TracingHandle

A running collector tracing setup: :class:TracingHandle plus the exporter endpoint.

stop

stop() -> None

Same as :meth:shutdown.

ConfigError

Bases: OtelCollectorError

Invalid or missing configuration.

ConflictError

Bases: OtelCollectorError

Conflict or failed precondition (HTTP 409, 412, CAS mismatch).

EnvReader

Reads GROW_<KEY_UPPER>_<NAME> and vendor variables from an injectable mapping.

Every getter returns None when no variable is set (empty strings count as unset). A present but invalid value raises :class:ConfigError that names the variable, never its value.

duration

duration(name: str, vendor_names: Iterable[str] = ()) -> builtins.float | None

Duration in seconds.

lookup

lookup(name: str, vendor_names: Iterable[str] = ()) -> tuple[str, str] | None

Return (variable_name, raw_value) for the first variable that is set.

ErrorCode

Bases: str, Enum

Canonical error codes; the value is the wire form used by the conformance suite.

ErrorInfo dataclass

Passed to Hooks.on_error; error is the (redacted) SDK error.

ExportResult dataclass

Outcome of one :meth:LogExporter.export call.

retries is a Python extension: the number of transport retries the export needed (summed into BatchStats.retries).

HealthStatus dataclass

Result of health(); status is ok/degraded/unhealthy/unreachable or a vendor word.

Hooks dataclass

Optional callbacks invoked on every attempt. Exceptions raised by hooks are ignored.

HttpTransport

Synchronous transport (one per client).

Service options (all optional):

  • request_id_headers: vendor request id headers, checked before :data:REQUEST_ID_HEADERS.
  • retry_after_headers: headers read (in order) for the delay a 429/503 response asks for; default ("retry-after",), e.g. ("retry-after", "x-ratelimit-reset"). See :func:retry_after_from_headers.
  • error_mapper: mapper(error, response) returns a service-specific error for an HTTP error response (or None to keep the default). The mapped error is what Hooks.on_error, the retry planner (retry_after) and the caller see; whether a status is retried stays the SPEC rule. Exceptions raised by the mapper are logged and ignored.

Every call after :meth:close raises :class:CancelledError ("client is closed").

close

close() -> None

Close the connection pool and abort backoff sleeps (idempotent).

request

request(req: Request, *, cancel: CancelToken | None = None) -> Response

Send req with retries; return the response or raise the mapped error.

LogClient

Bases: Protocol

Synchronous log client (SPEC LogClient).

LogExporter

Bases: Protocol

Synchronous exporter, called from the :class:BatchProcessor worker thread.

export sends one batch and reports how many records the service accepted. It may raise an SDK error instead of returning ExportResult(error=...); both count as failed records. timeout_s is the per-batch export budget the exporter should pass to its transport.

LogHandler

Bases: Handler

:class:logging.Handler that forwards records to a log client.

Attributes: extra= fields, logger.name, code.filepath/code.function/ code.lineno, thread.name and exception.* for exc_info. Records from loggers in exclude_loggers (prefix match; defaults to the HTTP stack the exporters use) and from the SDK's own worker threads are skipped to avoid feedback loops. When a formatter is set, the formatted text is the body; otherwise record.getMessage().

LogInput dataclass

Convenience input for :meth:LogClient.send; defaults are filled by the client.

LogQueryClient

Bases: Protocol

Synchronous query API. Services without a query API raise UnsupportedError.

LogRecord dataclass

One log record (OTel log data model subset). Treat instances as immutable.

from_json classmethod

from_json(data: Mapping[str, Any]) -> LogRecord

Parse the normalized wire form; raises ValidationError for malformed input.

json_size

json_size() -> int

UTF-8 byte size of the compact JSON form (used for maxBatchBytes).

to_json

to_json() -> dict[str, Any]

Normalized wire form (spec/schemas/log-record.schema.json, camelCase keys).

severity is the OTel number; timestamps are RFC 3339 UTC with microseconds.

to_json_str

to_json_str() -> str

Compact JSON text of :meth:to_json (UTF-8 safe, non-JSON values via str).

LogSearchResult dataclass

One page of search results.

LogSink

Bases: Protocol

Anything that accepts records: every log client.

Logger

Small structured logger writing to a :class:LogSink.

Records below min_severity are discarded. The sink fills timestamp, resource and trace correlation (the active OpenTelemetry span) for records without a trace id.

child

child(attributes: Mapping[str, AttrValue]) -> Logger

Logger with the same sink and level and the extra attributes.

LoggerLike

Bases: Protocol

Structured logger interface accepted in configuration (SPEC Logger).

MetricsApi

Instrument helpers bound to a meter source (a provider, or the global one).

counter

counter(name: str, *, unit: str = '', description: str = '', meter: str | None = None) -> Counter

Monotonic counter (OTLP sum, isMonotonic: true, cumulative).

gauge

gauge(name: str, *, unit: str = '', description: str = '', meter: str | None = None) -> Gauge

Synchronous gauge (OTLP gauge, last value).

histogram

histogram(name: str, *, unit: str = '', description: str = '', boundaries: Sequence[float] | None = None, meter: str | None = None) -> Histogram

Histogram with optional explicit bucket boundaries (ascending; SDK advice).

meter

meter(name: str = DEFAULT_METER_NAME, version: str | None = None) -> Meter

A meter from this source.

up_down_counter

up_down_counter(name: str, *, unit: str = '', description: str = '', meter: str | None = None) -> UpDownCounter

Up/down counter (OTLP sum, non-monotonic).

NotFoundError

Bases: OtelCollectorError

Missing record (HTTP 404).

OtelCollectorClient

Bases: _ClientBase

Synchronous OpenTelemetry Collector client. Thread-safe; use as a context manager or call :meth:close. Every I/O method accepts cancel= (a :class:CancelToken).

health_client property

health_client: CollectorHealthClient

The health client (health_check extension with zpages fallback).

close

close() -> None

Flush and shut down every handle, log client and exporter this client created, then release connections. Idempotent.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> OtelCollectorClient

Build a client from GROW_OPENTELEMETRY_COLLECTOR_*, GROW_OTEL_* and the standard OTEL_* variables (see :meth:OtelCollectorConfig.from_env).

health

health(*, cancel: CancelToken | None = None) -> HealthStatus

Unauthenticated health: GET {health_url} (port 13133), falling back to zpages when that endpoint is unreachable. Never raises for an unhealthy or unreachable collector (see :meth:CollectorHealthClient.health).

init_telemetry

init_telemetry(**kwargs: Any) -> TelemetryHandle

:func:init_telemetry with this client's config; :meth:close shuts it down.

init_tracing

init_tracing(config: TracingConfig | None = None, **kwargs: Any) -> CollectorTracingHandle

:func:init_tracing with this client's config as defaults; :meth:close shuts it down.

log_client

log_client(**kwargs: Any) -> BatchingLogClient

An OTLP :class:BatchingLogClient (:func:create_log_client); :meth:close flushes and closes it.

log_exporter

log_exporter() -> OtlpLogExporter

A bare :class:OtlpLogExporter for this config; :meth:close shuts it down.

log_query

log_query() -> CollectorLogQueryClient

Log query client: the collector has none, every method raises :class:UnsupportedError.

ping

ping(*, cancel: CancelToken | None = None) -> float

Authenticated round trip: an empty OTLP trace export (creates no telemetry) with the configured headers — POST {traces_url} with an empty protobuf body (HTTP) or TraceService/Export with an empty message (gRPC). Returns the latency in ms.

:class:AuthenticationError on 401 / gRPC UNAUTHENTICATED, :class:PermissionDeniedError on 403, :class:NotFoundError for a wrong path.

request

request(req: Request, *, cancel: CancelToken | None = None) -> Response

Send a raw request to the OTLP/HTTP receiver (retries, hooks, redaction).

server_version

server_version(*, cancel: CancelToken | None = None) -> str

Collector version from zpages /debug/servicez (works on stock stacks), else target_info at telemetry_url; :class:UnsupportedError when neither answers.

trace_query

trace_query() -> CollectorTraceQueryClient

Trace query client: the collector has none, every method raises :class:UnsupportedError.

wait_until_ready

wait_until_ready(timeout_s: float | timedelta = DEFAULT_READY_TIMEOUT_S, *, interval_s: float | timedelta = DEFAULT_READY_INTERVAL_S, cancel: CancelToken | None = None) -> HealthStatus

Poll :meth:health until healthy; :class:TimeoutError after timeout_s.

OtelCollectorConfig dataclass

Bases: BaseConfig

Immutable settings of :class:~grow_opentelemetry_collector.OtelCollectorClient and of the OTLP exporters (init_telemetry, init_tracing, log client, metrics).

Common fields (url, timeouts, retry, tls, proxy, headers, user_agent_suffix, hooks, logger) come from :class:BaseConfig; url is the OTLP/HTTP base URL (default http://127.0.0.1:4318). Durations are float seconds (timedelta accepted). The collector has no authentication of its own: credentials of a gateway or authenticator go in headers (redacted everywhere).

Fields left as None are derived: grpc_url = host of url on port 4317, health_url = port 13133 path /, zpages_url = port 55679, service_name = unknown_service:<executable>. Map fields (traces_batch: keys of :class:SpanBatchOptions; logs_batch: keys of :class:BatchOptions) hold only the settings that differ from the defaults.

See :meth:from_env for the environment variables.

endpoint_for

endpoint_for(signal: Signal) -> str

Export endpoint of a signal for the configured protocol: the explicit <signal>_url when set (in both protocols), else grpc_url for gRPC and url + /v1/<signal> for HTTP.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> _C

Build a validated config from the environment.

Precedence per field: explicit keyword > GROW_OPENTELEMETRY_COLLECTOR_<NAME> > GROW_OTEL_<NAME> > per-signal OTEL_EXPORTER_OTLP_<SIGNAL>_* > generic OTEL_* > default. Map fields (headers, resource_attributes, per-signal headers, batch settings) and tls merge key by key in the same order.

GROW_* names (after the prefix): URL, GRPC_URL, PROTOCOL, TRACES_URL, LOGS_URL, METRICS_URL, HEADERS (k=v,…), COMPRESSION, EXPORT_TIMEOUT, HEALTH_URL, ZPAGES_URL, TELEMETRY_URL, SERVICE_NAME, SERVICE_VERSION, ENVIRONMENT, RESOURCE_ATTRIBUTES, TRACES/LOGS/METRICS (bool), SAMPLER, SAMPLER_RATIO, PROPAGATORS, METRIC_EXPORT_INTERVAL, RUNTIME_METRICS, RESOURCE_DETECTORS (list or none) and the common CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY, PROXY.

OTEL_*: OTEL_EXPORTER_OTLP_ENDPOINT (→ url, or grpc_url for gRPC), …_PROTOCOL, …_HEADERS, …_COMPRESSION, …_TIMEOUT (ms), …_CERTIFICATE, …_CLIENT_CERTIFICATE, …_CLIENT_KEY, OTEL_EXPORTER_OTLP_{TRACES,LOGS,METRICS}_{ENDPOINT,HEADERS} (endpoints used as-is), OTEL_SERVICE_NAME (wins over service.name in OTEL_RESOURCE_ATTRIBUTES), OTEL_RESOURCE_ATTRIBUTES, OTEL_SDK_DISABLED, OTEL_{SIGNAL}_EXPORTER=none, OTEL_TRACES_SAMPLER/_ARG, OTEL_PROPAGATORS, OTEL_METRIC_EXPORT_INTERVAL, OTEL_BSP_* and OTEL_BLRP_*.

env defaults to os.environ. A present but invalid value raises :class:ConfigError naming the variable, never its value.

headers_for

headers_for(signal: Signal) -> dict[str, str]

Export headers of a signal: headers with the per-signal headers on top.

known_secrets

known_secrets() -> list[str]

Values of sensitive export headers (authorization, *token*, *key* …).

signal_url

signal_url(signal: Signal) -> str

OTLP/HTTP URL of a signal: the explicit <signal>_url, else url + /v1/<signal>.

validate

validate() -> _C

Common checks plus the collector rules; raises :class:ConfigError.

OtlpLogExporter

Bases: _ExporterBase

Synchronous :class:~grow_opentelemetry_collector.LogExporter sending OTLP logs to the collector (http/protobuf or grpc per the config).

HTTP uses the SDK transport (retries 429 and connection failures within export_timeout; other retryable errors are retried by the batch processor); gRPC retries UNAVAILABLE and RESOURCE_EXHAUSTED. A partial success reports rejected and a :class:ValidationError. Errors are returned in the result, never raised.

export

export(records: Sequence[LogRecord], *, gzip: bool = True, timeout_s: float = 30.0) -> ExportResult

Export records in one OTLP request and report accepted/rejected counts.

shutdown

shutdown() -> None

Release connections; later exports fail with a ValidationError. Idempotent.

PermissionDeniedError

Bases: OtelCollectorError

Authenticated but not allowed (HTTP 403).

PollingTail

tail built on search: a daemon thread polls for records newer than the last one.

Errors go to on_error (default: ignored) and polling continues. :meth:stop is idempotent.

poll_once

poll_once() -> int

Run one poll; returns the number of delivered records.

RateLimitError

Bases: OtelCollectorError

Too many requests (HTTP 429); retry_after holds the requested delay when known.

RedactionProcessor

Returns redacted copies of records.

Attribute names containing one of keys (case-insensitive substring) get replacement as value, recursively through nested mappings and lists. patterns (regular expressions or their source strings) are replaced in the body and in every string attribute value. :class:Secret values are always replaced.

is_sensitive

is_sensitive(name: str) -> bool

True when an attribute name matches one of the keys.

process

process(record: LogRecord) -> LogRecord

Redacted copy of record (the input is never modified).

redact_attributes

redact_attributes(attributes: Mapping[str, AttrValue]) -> dict[str, AttrValue]

Redacted copy of an attribute mapping.

redact_text

redact_text(text: str) -> str

Apply every pattern to text.

Request dataclass

One logical API call (possibly several attempts).

path is joined to the base URL ({name} style values must already be encoded; use :func:urllib.parse.quote); an absolute http:///https:// URL is used as is (for pagination links the service returns; the default headers, config.headers included, are sent there too, so only pass URLs of the same service). json is encoded when not None; content sends raw bytes. idempotent overrides the method rule; an idempotency_key sends the Idempotency-Key header and marks the request idempotent. raise_for_status=False returns error responses instead of raising (retries still apply). Statuses in allow_status are expected answers (a 404 that carries data, a health endpoint's 503): the response is returned at once, like a success, without retries or on_error.

RequestInfo dataclass

Passed to Hooks.on_request; url and headers are redacted.

ResourceRegistry

Holds :class:Stoppable objects; :meth:stop_all stops each once, ignoring errors.

register

register(item: Stoppable) -> None

Track item; when the registry is already closed the item is stopped now.

Response dataclass

A completed HTTP response (body fully read).

json

json() -> Any

Decode the body as JSON; :class:ValidationError when it is not valid JSON.

ResponseInfo dataclass

Passed to Hooks.on_response; headers are the redacted response headers (rate limit headers and the like stay readable).

RetryPolicy dataclass

Retry settings. Durations are seconds (datetime.timedelta is accepted).

Backoff for retry n (0-based) is full jitter: random(0, min(max_backoff, initial_backoff * multiplier ** n)).

random returns a float in [0, 1); inject it in tests for deterministic sleeps.

max_attempts property

max_attempts: int

Total attempts including the first one.

backoff

backoff(retry: int) -> float

Full-jitter sleep in seconds before retry retry (0-based).

backoff_cap

backoff_cap(retry: int) -> float

Upper bound of the jittered sleep before retry retry (0-based).

RuntimeMetricsHandle

Stops the runtime metrics callbacks (:func:register_runtime_metrics).

stopped property

stopped: bool

Whether :meth:stop was called.

stop

stop() -> None

Stop reporting (idempotent).

Secret

Wraps a credential so it never shows up in str/repr/logs.

s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')

reveal

reveal() -> str

Return the wrapped value.

Severity

Bases: IntEnum

Log severity; the values are the OpenTelemetry severity numbers.

from_python_level classmethod

from_python_level(level: int) -> Severity

Map a :mod:logging level (WARNING → WARN, CRITICAL → FATAL).

parse classmethod

parse(value: Severity | int | str) -> Severity

Parse a severity name ("warn", "WARNING", "critical") or OTel number (1-24).

Numbers inside a band map to the band start (10 → INFO). Raises ValidationError for anything else.

Span dataclass

A finished span as returned by a query API.

Ids are normalized on construction (an all-zero or empty parent_span_id becomes None); a negative duration_micros (the default) is computed from start and end. A subclass with normalize_ids = False keeps native ids verbatim (an empty parent_span_id still becomes None); link_class is used by :meth:from_json.

from_json classmethod

from_json(data: Mapping[str, Any]) -> Span

Parse the wire form; ValidationError for malformed input.

to_json

to_json() -> dict[str, Any]

Normalized wire form (camelCase, schema Span).

SpanBatchOptions dataclass

BatchSpanProcessor settings; durations are float seconds (timedelta accepted).

A link to another span. Set normalize_ids = False on a subclass for native ids.

SpanNode dataclass

A span with its children (sorted like :func:sort_spans).

find

find(name: str) -> SpanNode | None

Depth-first search for a node by span name.

SpanStatus dataclass

from_json classmethod

from_json(data: Any) -> SpanStatus

Parse {"code", "message"?} (a bare code string is accepted too).

TelemetryHandle

Bases: MetricsApi

A running telemetry setup (all three signals); see :func:init_telemetry.

Instrument helpers (meter, counter, up_down_counter, histogram, gauge) create instruments on this handle's meter provider (no-op when metrics are disabled).

is_shut_down property

is_shut_down: bool

Whether :meth:shutdown was called.

tracer_provider property

tracer_provider: TracerProvider | None

The tracer provider, when traces are enabled.

force_flush

force_flush(timeout_s: float | timedelta = 30.0) -> None

Export everything buffered in every enabled signal; :class:TimeoutError when it does not finish within timeout_s.

logger

logger(name: str | None = None, attributes: Mapping[str, AttrValue] | None = None) -> Logger

A :class:Logger writing to :attr:log_client (drops records when logs are disabled).

shutdown

shutdown() -> None

Flush and shut every provider down; idempotent. Unregisters the global meter provider of the module-level helpers. The first failure is raised after all providers were shut down.

tracer

tracer(name: str | None = None, version: str | None = None) -> otel_trace.Tracer

A tracer (non-recording when traces are disabled); name defaults to the service name.

TelemetryLogsOptions dataclass

Log settings of :func:init_telemetry.

batch defaults to the config's logs_batch; redaction to RedactionProcessor() (None disables it); min_severity applies to :meth:TelemetryHandle.logger. exporter replaces the OTLP exporter (tests).

TelemetryMetricsOptions dataclass

Metric settings of :func:init_telemetry (defaults from the config). exporter replaces the OTLP exporter (tests).

TelemetryTracesOptions dataclass

Trace settings of :func:init_telemetry (unset fields come from the collector config).

TimeoutError

Bases: OtelCollectorError

A connect, request or total deadline was exceeded (also HTTP 408, 504).

TlsConfig dataclass

TLS settings. insecure_skip_verify is for tests only and logs a warning once.

Trace dataclass

All spans of one trace, sorted by start time then span id.

A subclass with normalize_ids = False keeps a native trace id verbatim; span_class is used by :meth:from_json.

TraceQueryClient

Bases: Protocol

Synchronous trace query API.

TraceSearchQuery dataclass

matches

matches(trace: Trace) -> bool

Client-side filter: a span must match service/operation/tags; duration and time bounds apply to the whole trace.

TraceSummary dataclass

Search result row; normalize_ids = False on a subclass keeps native ids.

from_trace classmethod

from_trace(trace: Trace) -> TraceSummary

Summary of a trace (root = earliest span without a known parent).

to_json

to_json() -> dict[str, Any]

Wire form (traceSummary in trace.schema.json).

TracingASGIMiddleware

ASGI middleware: one SERVER span per HTTP request, parent taken from request headers.

Non-HTTP scopes (lifespan, websocket) and excluded_paths pass through untraced.

TracingConfig dataclass

Settings for :func:init_tracing_with. repr redacts credential headers.

protocol and endpoint are interpreted by the service's exporter factory; the template default protocol is http/protobuf. propagators beyond tracecontext, baggage, b3 and b3multi need a factory from the service package.

protocol and propagators remember whether the caller set them: left out (or passed as None) they read as :data:DEFAULT_TRACE_PROTOCOL / :data:DEFAULT_TRACE_PROPAGATORS exactly as before, and :attr:protocol_set / :attr:propagators_set are False so a service default can apply instead. The marker travels with the value, so :meth:with_changes, dataclasses.replace and TracingConfig(**fields) keep an unset field unset; passing the default value explicitly counts as set.

propagators_set property

propagators_set: bool

Whether propagators was given explicitly (False: the default applies).

protocol_set property

protocol_set: bool

Whether protocol was given explicitly (False: the default applies).

validate

validate() -> None

Raise ConfigError for invalid settings (never echoing values).

with_changes

with_changes(**changes: Any) -> TracingConfig

Copy with some fields replaced (unset protocol/propagators stay unset).

TracingHandle

Result of :func:init_tracing_with: provider, propagator, flush and shutdown.

force_flush

force_flush(timeout_s: float | timedelta | None = None) -> None

Export every finished span now; TimeoutError when it does not finish in time.

shutdown

shutdown() -> None

Flush and stop the provider and its exporter; idempotent.

tracer

tracer(name: str, version: str | None = None) -> otel_trace.Tracer

A tracer from this handle's provider (works with set_global=False too).

TracingWSGIMiddleware

WSGI middleware: one SERVER span per request; ends when the response is closed.

UnavailableError

Bases: OtelCollectorError

Network error or server unavailable (HTTP 500, 502, 503).

UnsupportedError

Bases: OtelCollectorError

The service or deployment does not offer this capability (HTTP 501, missing API).

ValidationError

Bases: OtelCollectorError

Bad input (HTTP 400, 413, 422, other 4xx, client-side validation).

add_event

add_event(name: str, attributes: Attributes = None) -> None

Add an event to the active span (no-op without one).

apoll_until async

apoll_until(fn: Callable[[], Awaitable[T | None]], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', clock: Callable[[], float] = time.monotonic) -> T

Async :func:poll_until; fn is an async callable.

async_httpx_event_hooks

async_httpx_event_hooks(*, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> dict[str, list[Callable[..., Any]]]

event_hooks for httpx.AsyncClient (same behaviour as :func:httpx_event_hooks).

async_wait_for_log async

async_wait_for_log(client: AsyncLogQueryClient, query: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, predicate: RecordPredicate | None = None) -> LogRecord

Async form of :func:wait_for_log.

async_wait_for_trace async

async_wait_for_trace(client: AsyncTraceQueryClient, trace_id: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, min_spans: int = 1, normalize: Callable[[str], str] | None = normalize_trace_id) -> Trace

Async form of :func:wait_for_trace.

build_propagator

build_propagator(names: Sequence[str], factories: Mapping[str, PropagatorFactory] | None = None) -> TextMapPropagator

Composite propagator for names; factories adds or overrides propagators by name.

build_resource

build_resource(config: TracingConfig) -> Resource

Resource with service.name/service.version/deployment.environment and extras.

The environment is written both as deployment.environment.name (current semantic conventions) and as the older deployment.environment. Merged on top of the SDK default resource (telemetry.sdk.*, OTEL_RESOURCE_ATTRIBUTES); explicit config values win.

build_sampler

build_sampler(name: str, ratio: float = 1.0) -> Sampler

OpenTelemetry sampler for a TracingConfig.sampler name.

build_tree

build_tree(spans: Iterable[Span]) -> list[SpanNode]

Parent/child forest; spans whose parent is missing become roots.

code_for_grpc_status

code_for_grpc_status(status: int) -> ErrorCode

Map a gRPC status code to an SDK :class:ErrorCode.

collector_span_exporter_factory

collector_span_exporter_factory(config: TracingConfig) -> SpanExporter

The OTLP span exporter for a tracing config (the exporter factory of init_tracing_with): http/protobuf → opentelemetry-exporter-otlp-proto-http, grpc → opentelemetry-exporter-otlp-proto-grpc (extra [grpc]). native raises :class:ConfigError. Retries follow the OTLP rules of the official exporter within batch.export_timeout_s.

container_id

container_id(read_file: ReadFile = _read_file) -> str | None

Container id from /proc/self/cgroup (v1) or /proc/self/mountinfo (v2); None outside a container.

counter

counter(name: str, *, unit: str = '', description: str = '', meter: str | None = None) -> Counter

Monotonic counter on the global provider.

create_async_log_client

create_async_log_client(config: OtelCollectorConfig | None = None, *, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _UNSET, correlate: bool = True, exporter: AsyncLogExporter | None = None) -> AsyncBatchingLogClient

Async :func:create_log_client (an :class:AsyncBatchingLogClient over :class:AsyncOtlpLogExporter); create it inside a running event loop.

create_log_client

create_log_client(config: OtelCollectorConfig | None = None, *, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _UNSET, correlate: bool = True, exporter: LogExporter | None = None) -> BatchingLogClient

A :class:BatchingLogClient exporting OTLP logs to the collector.

resource defaults to the configured resource attributes plus service.name, service.version and deployment.environment.name; options default to the configured logs_batch (OTEL_BLRP_*). redaction defaults to RedactionProcessor() (None disables it). config defaults to :meth:OtelCollectorConfig.from_env.

create_meter_provider

create_meter_provider(config: OtelCollectorConfig, *, resource: Resource, exporter: MetricExporter | None = None, export_interval_s: float | None = None) -> SdkMeterProvider

MeterProvider with a periodic reader (metric_export_interval) around the OTLP exporter (or exporter).

create_metric_exporter

create_metric_exporter(config: OtelCollectorConfig) -> MetricExporter

The official OTLP metric exporter for a collector config: http/protobuf → opentelemetry-exporter-otlp-proto-http ({metrics_url}), grpc → opentelemetry-exporter-otlp-proto-grpc. Cumulative temporality.

current_span

current_span() -> otel_trace.Span

The active span (a non-recording invalid span when none is active).

current_span_id

current_span_id() -> str | None

16-char lower-hex span id of the active span, or None.

current_trace_context

current_trace_context() -> tuple[str, str, int] | None

(trace_id, span_id, trace_flags) of the active OpenTelemetry span, if any.

current_trace_id

current_trace_id() -> str | None

32-char lower-hex trace id of the active span, or None.

datetime_to_micros

datetime_to_micros(value: datetime) -> int

Microseconds since the epoch (naive datetimes are UTC).

decode_rpc_status

decode_rpc_status(data: bytes) -> tuple[int | None, str | None] | None

Decode a binary google.rpc.Status (field 1 code, field 2 message).

Returns (code, message) or None when the bytes are not a well-formed Status.

default_tracer

default_tracer() -> otel_trace.Tracer

Tracer of this package from the global provider.

dependencies_from_spans

dependencies_from_spans(spans: Iterable[Span]) -> list[DependencyLink]

Service dependency links (parent service → child service, different services only).

detect_resource_attributes

detect_resource_attributes(detectors: Iterable[str] | None = None, *, env: Mapping[str, str] | None = None, read_file: ReadFile | None = None) -> dict[str, Any]

Detect resource attributes.

host: host.name, host.arch, os.type, os.version; process: process.pid, process.executable.*, process.runtime.*, process.command, process.owner; container: container.id from cgroups; k8s: k8s.pod.name, k8s.namespace.name … from the downward-API variables (K8S_*/POD_*), HOSTNAME and the service-account namespace file. Detectors that find nothing add nothing. detectors defaults to all of them.

encode_log_records

encode_log_records(records: Sequence[LogRecord]) -> ExportLogsServiceRequest

One ExportLogsServiceRequest for records (one ResourceLogs per distinct resource, scope :data:LOG_SCOPE_NAME). Timestamps become Unix nanoseconds, severity the OTel number, trace and span ids binary.

error_for_code

error_for_code(code: ErrorCode | str) -> type[OtelCollectorError]

Return the error class for a code (ErrorCode member or wire value).

error_for_grpc_status

error_for_grpc_status(operation: str, status: int, message: str | None, known_secrets: list[str] | None = None, retryable: bool | None = None) -> ServiceError

The SDK error for a gRPC status: "<op>: <message> (gRPC <NAME>)".

error_for_http_response

error_for_http_response(operation: str, resp: Response, known_secrets: list[str] | None = None) -> ServiceError

The SDK error for an OTLP/HTTP error response (status per SPEC 2.1, message from the JSON or protobuf google.rpc.Status body, retry_after on 429/503).

error_from_status

error_from_status(status: int, operation: str, *, content: bytes = b'', headers: Headers | None = None, known_secrets: list[str] | None = None, retry_after: float | None = None, request_id_headers: Sequence[str] = ()) -> ServiceError

Map an HTTP error status to the SPEC 2.1 error with a redacted, truncated message.

request_id_headers are checked before the default :data:REQUEST_ID_HEADERS.

extract

extract(carrier: Mapping[str, str], *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> otel_context.Context

Read a context from carrier (exact key match; use :func:extract_headers for HTTP).

extract_headers

extract_headers(headers: HeaderSource, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> otel_context.Context

Read a context from HTTP headers (case-insensitive; mapping or ASGI-style byte pairs).

format_timestamp

format_timestamp(value: datetime) -> str

RFC 3339 UTC form with microseconds and Z; naive datetimes are taken as UTC.

gauge

gauge(name: str, *, unit: str = '', description: str = '', meter: str | None = None) -> Gauge

Synchronous gauge on the global provider.

get_logger

get_logger() -> logging.Logger

The package logger (LOGGER_NAME), silent by default (NullHandler).

grpc_call

grpc_call(channel: Channel, operation: str, path: str, payload: bytes, *, metadata: list[tuple[str, str]], timeout: float, retry: RetryPolicy, gzip: bool = False, known_secrets: Callable[[], list[str]] = list, cancel: CancelToken | None = None) -> bytes

One unary OTLP call with raw protobuf bytes; retries retryable statuses (UNAVAILABLE, RESOURCE_EXHAUSTED …) with retry backoff. Returns the response bytes.

grpc_call_async async

grpc_call_async(channel: Channel, operation: str, path: str, payload: bytes, *, metadata: list[tuple[str, str]], timeout: float, retry: RetryPolicy, gzip: bool = False, known_secrets: Callable[[], list[str]] = list) -> bytes

Async :func:grpc_call; cancel by cancelling the task (raises :class:CancelledError).

grpc_credentials

grpc_credentials(url: str, tls: TlsConfig | None) -> grpc.ChannelCredentials | None

TLS channel credentials for an https:// target or when TLS material is set; None for plaintext. insecure_skip_verify raises :class:ConfigError (grpcio cannot skip certificate verification).

grpc_metadata

grpc_metadata(headers: Mapping[str, str]) -> list[tuple[str, str]]

gRPC metadata from export headers (names lower-cased).

grpc_target

grpc_target(url: str) -> str

host:port of a gRPC URL (http://collector:4317 → collector:4317).

histogram

histogram(name: str, *, unit: str = '', description: str = '', boundaries: Sequence[float] | None = None, meter: str | None = None) -> Histogram

Histogram on the global provider.

httpx_event_hooks

httpx_event_hooks(*, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> dict[str, list[Callable[..., Any]]]

event_hooks for httpx.Client: a CLIENT span per request with injected headers.

A request that fails before a response arrives (connection error) never reaches the response hook, so its span is not exported; use :func:instrument_requests_session style wrapping or with_span around the call when such failures must be traced.

init_telemetry

init_telemetry(config: OtelCollectorConfig | None = None, *, env: Mapping[str, str] | Literal[False] | None = None, traces: bool | TelemetryTracesOptions | None = None, logs: bool | TelemetryLogsOptions | None = None, metrics: bool | TelemetryMetricsOptions | None = None, set_global: bool = True, detectors: Sequence[str] | None = None, detect_env: Mapping[str, str] | None = None, read_file: ReadFile | None = None) -> TelemetryHandle

One-call OpenTelemetry bootstrap for every Grow stack (the platform deploys the collector with each stack).

Traces (:func:init_tracing), logs (:class:OtlpLogExporter + BatchingLogClient) and metrics (MeterProvider + OTLP exporter) share one resource: detected attributes (resource_detectors) < config resource_attributes < service fields. Signals follow the config (traces/logs/metrics, OTEL_SDK_DISABLED, OTEL_<SIGNAL>_EXPORTER=none) unless traces/logs/metrics turn them on (True or options) or off (False). config defaults to :meth:OtelCollectorConfig.from_env over env (env=False ignores the environment). With set_global the tracer provider, propagator and meter provider become the globals used by with_span, counter() … Exporter failures never raise at the caller.

init_tracing

init_tracing(config: TracingConfig | None = None, *, collector: OtelCollectorConfig | None = None, env: Mapping[str, str] | Literal[False] | None = None, propagator_factories: Mapping[str, PropagatorFactory] | None = None, span_processors: Sequence[SpanProcessor] = (), id_generator: IdGenerator | None = None, **overrides: Any) -> CollectorTracingHandle

Set up OpenTelemetry tracing that exports to an OpenTelemetry Collector (SPEC §5).

OTLP http/protobuf to http://127.0.0.1:4318/v1/traces by default, or grpc to http://127.0.0.1:4317. Pass a :class:TracingConfig and/or its fields as keywords (service_name="checkout", protocol="grpc"). Unset fields come from collector (default :meth:OtelCollectorConfig.from_env over env; env=False ignores the environment), i.e. GROW_OPENTELEMETRY_COLLECTOR_*, GROW_OTEL_* and the standard OTEL_* variables. Raises :class:ConfigError for invalid settings.

init_tracing_with

init_tracing_with(config: TracingConfig, exporter_factory: ExporterFactory, *, propagator_factories: Mapping[str, PropagatorFactory] | None = None, span_processors: Sequence[SpanProcessor] = (), id_generator: IdGenerator | None = None, sampler: Sampler | None = None) -> TracingHandle

Build a TracerProvider for config with a BatchSpanProcessor around the exporter.

Services wrap this in their init_tracing(config). propagator_factories lets a service add datadog/sw8 style propagators; span_processors (extra processors, e.g. a second exporter) are added after the batch processor; sampler replaces the one built from config.sampler/sampler_ratio (remote or vendor samplers). With config.set_global the provider and propagator become the OpenTelemetry globals (the API allows one global provider per process: is_global on the handle tells whether it took effect).

inject

inject(carrier: MutableMapping[str, str] | None = None, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> MutableMapping[str, str]

Write the current (or given) context into carrier and return it.

Uses propagator or the global propagator (set by init_tracing_with).

inject_headers

inject_headers(headers: MutableMapping[str, str] | None = None, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> MutableMapping[str, str]

Add propagation headers (traceparent, baggage …) to headers and return them.

instrument_requests_session

instrument_requests_session(session: Session, *, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> requests.Session

Trace every request sent through session (CLIENT span, headers injected).

Wraps session.send once; calling it again on the same session is a no-op.

mark_span_error

mark_span_error(span: Span, error: BaseException | str) -> None

Set ERROR status on span and record the exception (when error is one).

meter

meter(name: str = DEFAULT_METER_NAME, version: str | None = None) -> Meter

A meter from the global provider (set by init_telemetry unless set_global=False).

micros_to_datetime

micros_to_datetime(micros: int) -> datetime

Exact UTC datetime for microseconds since the epoch.

new_idempotency_key

new_idempotency_key() -> str

A random key for the Idempotency-Key header.

normalize_headers

normalize_headers(headers: HeaderSource) -> dict[str, list[str]]

Lower-cased header names → values; accepts mappings and (name, value) pairs incl. bytes.

normalize_span_id

normalize_span_id(value: str | int | bytes) -> str

16-char lower-hex span id (left-padded); raises ValidationError when invalid.

normalize_trace_id

normalize_trace_id(value: str | int | bytes) -> str

32-char lower-hex trace id; 64-bit ids (16 hex chars, ints, 8 bytes) are left-padded.

Raises ValidationError for non-hex, too long or all-zero ids.

open_aio_channel

open_aio_channel(url: str, tls: TlsConfig | None) -> grpc.aio.Channel

An asyncio gRPC channel for url.

open_channel

open_channel(url: str, tls: TlsConfig | None) -> grpc.Channel

A sync gRPC channel for url.

otlp_error_text

otlp_error_text(body: bytes | str | None, known_secrets: list[str] | None = None) -> str | None

Human text of an OTLP error body: JSON {"code","message"}, a binary google.rpc.Status or plain text. Redacted, truncated to 300 characters; None for an empty body.

parse_bool

parse_bool(text: str) -> bool

Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.

parse_duration

parse_duration(text: str) -> float

Parse a duration into seconds.

Accepts integer milliseconds ("1500" → 1.5) or Go-style units ("500ms", "10s", "2m", "1h", "1m30s"). Raises :class:ValueError for anything else.

parse_key_value_list

parse_key_value_list(raw: str, source: str) -> dict[str, str]

Parse k=v,k2=v2 (values percent-decoded) as used by OTEL_EXPORTER_OTLP_HEADERS and OTEL_RESOURCE_ATTRIBUTES.

Raises :class:ConfigError naming source (never the value) on malformed input.

parse_retry_after

parse_retry_after(value: str | None, *, now: Callable[[], float] = time.time) -> float | None

Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.

parse_servicez_version

parse_servicez_version(html: str) -> str | None

Collector version from the zpages /debug/servicez HTML (leading v removed); None when absent.

parse_target_info_version

parse_target_info_version(metrics: str) -> str | None

service_version of a Prometheus target_info series (leading v removed); None when absent.

parse_timestamp

parse_timestamp(value: str) -> datetime

Parse RFC 3339 (any fraction precision, Z/offset; none = UTC) to aware UTC.

pem_file

pem_file(pem: str) -> str

Write an inline PEM bundle to a private temp file (removed at exit); return its path.

poll_until

poll_until(fn: Callable[[], T | None], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic) -> T

Call fn every interval_s until it returns a ready value; return that value.

A value is ready when it is not None and predicate(value) is true (without a predicate: not an empty container). Retryable SDK errors raised by fn are remembered and polling continues; other errors propagate. Raises :class:TimeoutError after timeout_s.

read_tls_file

read_tls_file(path: str | None) -> bytes | None

Bytes of a TLS file; :class:ConfigError (without the path) when unreadable.

record_exception

record_exception(error: BaseException, attributes: Attributes = None) -> None

Record error as an exception event on the active span (status unchanged).

redact_fields

redact_fields(value: Any, extra_keys: Iterable[str] = ()) -> Any

Recursively redact values whose key looks sensitive in nested mappings and lists.

redact_headers

redact_headers(headers: Mapping[str, str] | Iterable[tuple[str, str]]) -> dict[str, str]

Copy of headers with sensitive values replaced by [REDACTED].

redact_text

redact_text(text: str, known_secrets: Iterable[str | Secret | None] = ()) -> str

Replace every known secret value (length >= 4) in text with [REDACTED].

redact_url

redact_url(url: str) -> str

Redact user info and every query value (all values, not only sensitive ones).

Query names are kept so the URL stays useful in logs.

register_runtime_metrics

register_runtime_metrics(meter_instance: Meter) -> RuntimeMetricsHandle

Register Python runtime metrics on meter_instance: process.memory.usage (RSS, By), process.cpu.time (s, cpu.mode user/system), process.thread.count, cpython.gc.collections (per cpython.gc.generation) and process.uptime (s).

resolve_traces_endpoint

resolve_traces_endpoint(protocol: str, endpoint: str | None = None) -> str

Traces exporter URL: for http/protobuf an endpoint without a path (a base such as http://collector:4318) gets /v1/traces; anything else is used as-is. Without an endpoint: the collector default for the protocol.

retry_after_from_headers

retry_after_from_headers(headers: Headers | Mapping[str, str], names: Sequence[str] = RETRY_AFTER_HEADERS, *, now: Callable[[], float] = time.time) -> float | None

Server requested delay in seconds from the first of names that parses.

Retry-After is delta seconds or an HTTP-date. Other headers (X-RateLimit-Reset, RateLimit-Reset …) may be delta seconds or a Unix timestamp in seconds or milliseconds; timestamps are turned into the remaining delay.

set_error

set_error(error: BaseException | str) -> None

Mark the active span as failed: ERROR status, plus an exception event for exceptions.

set_global_meter_provider

set_global_meter_provider(provider: MeterProvider | None) -> Callable[[], None]

Make provider the target of the module-level helpers (counter() …) and, when no global provider was set yet, the OpenTelemetry global. Returns a function that undoes the helper registration (the OpenTelemetry global can be set only once per process).

sort_spans

sort_spans(spans: Iterable[Span]) -> list[Span]

Spans sorted by start time, then span id.

span_from_readable

span_from_readable(span: ReadableSpan) -> Span

Convert a finished OpenTelemetry SDK span (e.g. from an in-memory exporter).

span_kind

span_kind(kind: SpanKindLike) -> SpanKind

SpanKind from an enum member or a name ("server"); None → INTERNAL.

split_url

split_url(url: str) -> tuple[str, str]

(scheme://host:port, /path?query) of an absolute URL (path defaults to /).

structlog_processor

structlog_processor(client: LogSink) -> StructlogProcessor

Return a structlog processor that sends every event to client.

The event dict passes through unchanged, so put this processor before the renderer. event becomes the body, level (or the method name) the severity, timestamp (TimeStamper output, epoch float or datetime) the timestamp; exc_info and a rendered exception become exception.* attributes; every other key is an attribute.

telemetry_resource_attributes

telemetry_resource_attributes(config: OtelCollectorConfig, *, detectors: Sequence[str] | None = None, env: Mapping[str, str] | None = None, read_file: ReadFile | None = None) -> dict[str, Any]

Resource attributes for a config: detected < config attributes < service fields (service.name, service.version, deployment.environment[.name]).

to_any_value

to_any_value(value: Any) -> AnyValue

OTLP AnyValue for an attribute value (scalars, lists, nested mappings, bytes).

to_attr_value

to_attr_value(value: Any) -> AttrValue

Convert any Python value to an attribute value (unknown types become str(value)).

to_seconds

to_seconds(value: float | timedelta) -> float

Normalise a duration given as float seconds or :class:datetime.timedelta.

trace_fields

trace_fields() -> dict[str, str]

{"trace_id": …, "span_id": …} of the active span for log fields; {} without one.

traced

traced(fn: Callable[P, R]) -> Callable[P, R]
traced(name: str | None = None, /, *, attributes: Attributes = None, kind: SpanKindLike = None, tracer: Tracer | None = None) -> Callable[[Callable[P, R]], Callable[P, R]]
traced(name_or_fn: str | Callable[P, R] | None = None, /, *, attributes: Attributes = None, kind: SpanKindLike = None, tracer: Tracer | None = None) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]

Decorator that runs a function (sync or async def) inside a span.

@traced, @traced() and @traced("name") all work; the default span name is the function's qualified name. Async generators are not supported (the span would end before iteration).

tracing_config_from

tracing_config_from(collector: OtelCollectorConfig, config: TracingConfig | None = None, **overrides: Any) -> TracingConfig

The effective :class:TracingConfig: explicit settings (fields of config that differ from the defaults, plus overrides) over :func:tracing_defaults.

resource_attributes and headers merge key by key (explicit wins); an explicit endpoint is resolved with :func:resolve_traces_endpoint; an explicit protocol without an endpoint switches to the collector's grpc_url / traces URL.

tracing_defaults

tracing_defaults(collector: OtelCollectorConfig) -> dict[str, Any]

:class:TracingConfig fields derived from a collector config (used beneath explicit tracing settings): service, resource, endpoint, protocol, headers, sampler, propagators, batch (export_timeout + traces_batch), TLS and compression.

transport_config

transport_config(cfg: OtelCollectorConfig, url: str, headers: Mapping[str, str] | None = None) -> BaseConfig

The transport settings of cfg for another base url; headers default to none (admin endpoints are unauthenticated).

truncate

truncate(text: str, limit: int = 300) -> str

Truncate text to limit characters (adds an ellipsis when cut).

up_down_counter

up_down_counter(name: str, *, unit: str = '', description: str = '', meter: str | None = None) -> UpDownCounter

Up/down counter on the global provider.

user_agent

user_agent(suffix: str | None = None) -> str

grow-codes-<key>/<version> (python) plus <suffix> when given.

wait_for_log

wait_for_log(client: LogQueryClient, query: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, predicate: RecordPredicate | None = None) -> LogRecord

Poll client.search(query) until a record (matching predicate) shows up.

wait_for_trace

wait_for_trace(client: TraceQueryClient, trace_id: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, min_spans: int = 1, normalize: Callable[[str], str] | None = normalize_trace_id) -> Trace

Poll get_trace until the trace has min_spans spans; TimeoutError otherwise.

NotFoundError and retryable errors count as "not there yet". normalize turns trace_id into the id passed to get_trace (default: 32-char lower hex); None passes native ids verbatim.

with_span

with_span(name: str, fn: None = None, *, attributes: Attributes = None, kind: SpanKindLike = None, links: Sequence[Link | SpanContext] | None = None, tracer: Tracer | None = None) -> AbstractContextManager[otel_trace.Span]
with_span(name: str, fn: Callable[[Span], R], *, attributes: Attributes = None, kind: SpanKindLike = None, links: Sequence[Link | SpanContext] | None = None, tracer: Tracer | None = None) -> R
with_span(name: str, fn: Callable[[Span], R] | None = None, *, attributes: Attributes = None, kind: SpanKindLike = None, links: Sequence[Link | SpanContext] | None = None, tracer: Tracer | None = None) -> R | AbstractContextManager[otel_trace.Span]

Run fn(span) inside a new current span, or return a context manager without fn.

The span always ends. An exception is recorded, sets ERROR status and is re-raised (cancellation, asyncio.CancelledError or the SDK CancelledError, is not). The context-manager form also works inside async code (context is kept in contextvars).