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
¶
Attribute value: scalar, list of values or nested mapping (OTel AnyValue without bytes).
AsyncBaseLogQueryClient ¶
Async :class:BaseLogQueryClient.
AsyncBaseTraceQueryClient ¶
Async :class:BaseTraceQueryClient.
query_trace_id ¶
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 ¶
Queue without blocking; False when dropped (block acts as drop_newest here).
add_wait
async
¶
Queue a record, waiting for queue space with drop_policy="block".
flush
async
¶
Export everything queued now; raises TimeoutError when timeout_s passes first.
shutdown
async
¶
Drain (bounded by timeout_s), stop the task, shut the exporter down; idempotent.
AsyncBatchingLogClient ¶
Bases: _ClientBase
:class:AsyncLogClient over an :class:AsyncLogExporter + :class:AsyncBatchProcessor.
AsyncCollectorHealthClient ¶
Asynchronous :class:CollectorHealthClient; cancel a call by cancelling its task.
from_env
classmethod
¶
Build from the environment (see :meth:OtelCollectorConfig.from_env).
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 ¶
AsyncCollectorTraceQueryClient ¶
Async TraceQueryClient of the collector: every method raises
: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").
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.
aclose
async
¶
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
¶
See :meth:OtelCollectorClient.from_env.
init_telemetry ¶
:func:init_telemetry with this client's config; :meth:aclose shuts it down.
init_tracing ¶
:func:init_tracing with this client's config as defaults; :meth:aclose shuts it
down.
log_client ¶
An OTLP :class:AsyncBatchingLogClient (:func:create_async_log_client); call it
inside a running event loop. :meth:aclose flushes and closes it.
log_exporter ¶
A bare :class:AsyncOtlpLogExporter; :meth:aclose shuts it down.
log_query ¶
Async log query client: every method raises :class:UnsupportedError.
trace_query ¶
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 ¶
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
¶
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 ¶
Revealed values of every :class:Secret field (used to redact error text).
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 ¶
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
¶
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 ¶
Queue a record; False when it was dropped. Blocks only with drop_policy="block".
flush ¶
Export everything queued now; raises TimeoutError when timeout_s passes first.
shutdown ¶
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.
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.
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=.
from_env
classmethod
¶
Build from the environment (see :meth:OtelCollectorConfig.from_env).
health ¶
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 ¶
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 ¶
CollectorTraceQueryClient ¶
CollectorTracingHandle ¶
Bases: TracingHandle
A running collector tracing setup: :class:TracingHandle plus the exporter
endpoint.
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.
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 (orNoneto keep the default). The mapped error is whatHooks.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").
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
¶
Parse the normalized wire form; raises ValidationError for malformed input.
to_json ¶
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 ¶
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 ¶
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 ¶
Monotonic counter (OTLP sum, isMonotonic: true, cumulative).
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 ¶
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
¶
The health client (health_check extension with zpages fallback).
close ¶
Flush and shut down every handle, log client and exporter this client created, then release connections. Idempotent.
from_env
classmethod
¶
Build a client from GROW_OPENTELEMETRY_COLLECTOR_*, GROW_OTEL_* and the
standard OTEL_* variables (see :meth:OtelCollectorConfig.from_env).
health ¶
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 ¶
:func:init_telemetry with this client's config; :meth:close shuts it down.
init_tracing ¶
:func:init_tracing with this client's config as defaults; :meth:close shuts it
down.
log_client ¶
An OTLP :class:BatchingLogClient (:func:create_log_client); :meth:close
flushes and closes it.
log_exporter ¶
A bare :class:OtlpLogExporter for this config; :meth:close shuts it down.
log_query ¶
Log query client: the collector has none, every method raises
:class:UnsupportedError.
ping ¶
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 ¶
Send a raw request to the OTLP/HTTP receiver (retries, hooks, redaction).
server_version ¶
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 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 ¶
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
¶
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 ¶
Export headers of a signal: headers with the per-signal headers on top.
known_secrets ¶
Values of sensitive export headers (authorization, *token*, *key* …).
signal_url ¶
OTLP/HTTP URL of a signal: the explicit <signal>_url, else url +
/v1/<signal>.
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.
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.
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.
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 ¶
Track item; when the registry is already closed the item is stopped now.
Response
dataclass
¶
A completed HTTP response (body fully read).
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.
RuntimeMetricsHandle ¶
Secret ¶
Wraps a credential so it never shows up in str/repr/logs.
s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')
Severity ¶
Bases: IntEnum
Log severity; the values are the OpenTelemetry severity numbers.
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.
SpanBatchOptions
dataclass
¶
BatchSpanProcessor settings; durations are float seconds (timedelta accepted).
SpanLink
dataclass
¶
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).
SpanStatus
dataclass
¶
from_json
classmethod
¶
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).
tracer_provider
property
¶
The tracer provider, when traces are enabled.
force_flush ¶
Export everything buffered in every enabled signal; :class:TimeoutError when it
does not finish within timeout_s.
logger ¶
A :class:Logger writing to :attr:log_client (drops records when logs are
disabled).
shutdown ¶
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 ¶
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 ¶
Client-side filter: a span must match service/operation/tags; duration and time bounds apply to the whole trace.
TraceSummary
dataclass
¶
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.
TracingHandle ¶
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 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 ¶
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 ¶
OpenTelemetry sampler for a TracingConfig.sampler name.
build_tree ¶
Parent/child forest; spans whose parent is missing become roots.
code_for_grpc_status ¶
Map a gRPC status code to an SDK :class:ErrorCode.
collector_span_exporter_factory ¶
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 from /proc/self/cgroup (v1) or /proc/self/mountinfo (v2);
None outside a container.
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 ¶
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 ¶
The active span (a non-recording invalid span when none is active).
current_span_id ¶
16-char lower-hex span id of the active span, or None.
current_trace_context ¶
(trace_id, span_id, trace_flags) of the active OpenTelemetry span, if any.
current_trace_id ¶
32-char lower-hex trace id of the active span, or None.
datetime_to_micros ¶
Microseconds since the epoch (naive datetimes are UTC).
decode_rpc_status ¶
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 ¶
Tracer of this package from the global provider.
dependencies_from_spans ¶
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 ¶
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 ¶
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 ¶
RFC 3339 UTC form with microseconds and Z; naive datetimes are taken as UTC.
gauge ¶
Synchronous gauge on the global provider.
get_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 ¶
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 from export headers (names lower-cased).
grpc_target ¶
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 ¶
Set ERROR status on span and record the exception (when error is one).
meter ¶
A meter from the global provider (set by init_telemetry unless
set_global=False).
micros_to_datetime ¶
Exact UTC datetime for microseconds since the epoch.
normalize_headers ¶
Lower-cased header names → values; accepts mappings and (name, value) pairs incl. bytes.
normalize_span_id ¶
16-char lower-hex span id (left-padded); raises ValidationError when invalid.
normalize_trace_id ¶
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 ¶
An asyncio gRPC channel for url.
open_channel ¶
A sync gRPC channel for url.
otlp_error_text ¶
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 true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.
parse_duration ¶
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 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 as delta seconds or an HTTP-date; return seconds (>= 0) or None.
parse_servicez_version ¶
Collector version from the zpages /debug/servicez HTML (leading v removed);
None when absent.
parse_target_info_version ¶
service_version of a Prometheus target_info series (leading v removed);
None when absent.
parse_timestamp ¶
Parse RFC 3339 (any fraction precision, Z/offset; none = UTC) to aware UTC.
pem_file ¶
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 ¶
Bytes of a TLS file; :class:ConfigError (without the path) when unreadable.
record_exception ¶
Record error as an exception event on the active span (status unchanged).
redact_fields ¶
Recursively redact values whose key looks sensitive in nested mappings and lists.
redact_headers ¶
Copy of headers with sensitive values replaced by [REDACTED].
redact_text ¶
Replace every known secret value (length >= 4) in text with [REDACTED].
redact_url ¶
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 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 ¶
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 ¶
Mark the active span as failed: ERROR status, plus an exception event for exceptions.
set_global_meter_provider ¶
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 ¶
Spans sorted by start time, then span id.
span_from_readable ¶
Convert a finished OpenTelemetry SDK span (e.g. from an in-memory exporter).
span_kind ¶
SpanKind from an enum member or a name ("server"); None → INTERNAL.
split_url ¶
(scheme://host:port, /path?query) of an absolute URL (path defaults to /).
structlog_processor ¶
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 ¶
OTLP AnyValue for an attribute value (scalars, lists, nested mappings, bytes).
to_attr_value ¶
Convert any Python value to an attribute value (unknown types become str(value)).
to_seconds ¶
Normalise a duration given as float seconds or :class:datetime.timedelta.
trace_fields ¶
{"trace_id": …, "span_id": …} of the active span for log fields; {} without one.
traced ¶
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 ¶
: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 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 ¶
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: 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).