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 Jaeger.
from grow_jaeger import JaegerClient, JaegerConfig client = JaegerClient.from_env() # doctest: +SKIP
Modules: :class:JaegerClient / :class:AsyncJaegerClient (health, ping, version),
:class:JaegerQueryClient (trace query API), :func:init_tracing (OTLP export preset) and
:class:JaegerRemoteSampler (remote sampling), plus the shared tracing helpers.
JaegerBuildInfo
module-attribute
¶
Build information embedded in the Jaeger UI (gitVersion, gitCommit, buildDate).
AsyncBaseTraceQueryClient ¶
Async :class:BaseTraceQueryClient.
query_trace_id ¶
The id wait_for_trace passes to get_trace; override to keep native ids.
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").
AsyncJaegerClient ¶
Asynchronous Jaeger 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. Tracing handles and remote samplers are thread based
and shared with the sync API.
query
property
¶
The async trace query client (shares this client's connections).
aclose
async
¶
Shut down tracing handles and samplers, close connections (idempotent).
from_env
classmethod
¶
Build a client from the environment (see :meth:JaegerClient.from_env).
init_tracing ¶
See :meth:JaegerClient.init_tracing.
remote_sampler ¶
remote_sampler(service: str, poll_interval_s: float | timedelta = DEFAULT_SAMPLING_POLL_INTERVAL_S, *, sampling_url: str | None = None, initial_sampling_rate: float = DEFAULT_INITIAL_SAMPLING_RATE, **kwargs: Any) -> JaegerRemoteSampler
See :meth:JaegerClient.remote_sampler.
sampling_strategy
async
¶
See :meth:JaegerClient.sampling_strategy.
AsyncJaegerQueryClient ¶
Bases: AsyncBaseTraceQueryClient
Asynchronous :class:JaegerQueryClient (implements
:class:~grow_jaeger.AsyncTraceQueryClient); cancel a call by cancelling its task.
find_traces
async
¶
See :meth:JaegerQueryClient.find_traces.
from_env
classmethod
¶
Standalone async query client from the environment.
get_dependencies
async
¶
get_dependencies(end_ts: datetime | None = None, lookback_s: float | timedelta | None = None, *, start: datetime | None = None, end: datetime | None = None, service: str | None = None) -> list[DependencyLink]
See :meth:JaegerQueryClient.get_dependencies.
get_operations
async
¶
See :meth:JaegerQueryClient.get_operations.
get_trace
async
¶
get_trace(trace_id: str, *, start: datetime | None = None, end: datetime | None = None, raw_traces: bool | None = None) -> Trace | None
See :meth:JaegerQueryClient.get_trace.
list_operations
async
¶
See :meth:JaegerQueryClient.list_operations.
require_trace
async
¶
require_trace(trace_id: str, *, start: datetime | None = None, end: datetime | None = None, raw_traces: bool | None = None) -> Trace
See :meth:JaegerQueryClient.require_trace.
search_traces
async
¶
See :meth:JaegerQueryClient.search_traces.
AsyncTraceQueryClient ¶
Bases: Protocol
Asynchronous trace query API (same methods, awaited).
AuthenticationError ¶
Bases: JaegerError
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.
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.
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: JaegerError, 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.
ConfigError ¶
Bases: JaegerError
Invalid or missing configuration.
ConflictError ¶
Bases: JaegerError
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.
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").
JaegerClient ¶
Synchronous Jaeger client. Thread-safe; use as a context manager or call :meth:close.
Every I/O method accepts cancel= (a :class:CancelToken) to abort from another thread.
:meth:close also shuts down every tracing handle and remote sampler created through the
client.
query
property
¶
The trace query client (shares this client's connections).
resources
property
¶
Background resources (tracing handles, samplers) stopped by :meth:close.
build_info ¶
Build information parsed from the UI page (GET /); None when absent.
close ¶
Shut down tracing handles (flushing them) and samplers, close connections (idempotent).
from_env
classmethod
¶
Build a client from GROW_JAEGER_* and the vendor variables (JAEGER_QUERY_URL,
JAEGER_SAMPLING_ENDPOINT).
health ¶
Liveness of the query service: GET / (the stack catalog health target).
With health_url set, the healthcheckv2 /status answer decides and adds detail.
Never raises for an unhealthy or unreachable service (only CANCELLED/CONFIG).
init_tracing ¶
Start OpenTelemetry tracing to Jaeger (see :func:grow_jaeger.init_tracing). The
handle is shut down by :meth:close.
ping ¶
Round trip through the query API (GET /api/v3/services); latency in ms.
remote_sampler ¶
remote_sampler(service: str, poll_interval_s: float | timedelta = DEFAULT_SAMPLING_POLL_INTERVAL_S, *, sampling_url: str | None = None, initial_sampling_rate: float = DEFAULT_INITIAL_SAMPLING_RATE, **kwargs: Any) -> JaegerRemoteSampler
A :class:JaegerRemoteSampler with this client's settings (sampling_url,
timeouts, TLS, proxy, headers, token); closed by :meth:close.
request ¶
Send a raw request to the query API (retries, hooks, redaction).
sampling_strategy ¶
The remote sampling strategy of service (one GET {sampling_url}?service=).
server_version ¶
Server version without the leading v (2.23.0).
Parsed from JAEGER_VERSION in the UI page, else from target_info at
metrics_url. :class:UnsupportedError when neither reports one.
JaegerConfig
dataclass
¶
Bases: BaseConfig
Immutable settings for :class:~grow_jaeger.JaegerClient.
Common fields (url, timeouts, retry, tls, proxy, headers,
user_agent_suffix, hooks, logger) come from :class:BaseConfig. Durations are
float seconds; datetime.timedelta is accepted. token accepts a str and is stored
as a :class:Secret; repr() never shows it.
Attributes:
| Name | Type | Description |
|---|---|---|
url |
str
|
query API base URL (port 16686). A reverse-proxy base path is kept
( |
token |
Secret | None
|
optional bearer token sent as |
sampling_url |
str
|
remote sampling endpoint (port 5778, path |
health_url |
str | None
|
optional healthcheckv2 |
metrics_url |
str | None
|
optional Prometheus |
Environment (from_env), prefix GROW_JAEGER_: URL (then JAEGER_QUERY_URL),
TOKEN, SAMPLING_URL (then JAEGER_SAMPLING_ENDPOINT), HEALTH_URL,
METRICS_URL, CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT,
MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY,
PROXY.
JaegerOperation
dataclass
¶
One operation of a service as reported by /api/v3/operations.
JaegerQueryClient ¶
Bases: BaseTraceQueryClient
Synchronous trace query client (implements :class:~grow_jaeger.TraceQueryClient).
Get one from :attr:JaegerClient.query <grow_jaeger.JaegerClient.query> (shares the
client's connections) or construct it from a config (owns its connections; call
:meth:close or use it as a context manager). Every method accepts cancel=.
find_traces ¶
find_traces(query: TraceSearchQuery | None = None, *, cancel: CancelToken | None = None, **filters: Any) -> list[Trace]
Full traces matching a search: GET /api/v3/traces.
Pass a :class:TraceSearchQuery / :class:JaegerTraceQuery or its fields as keywords
(service, operation, tags, min_duration_micros, max_duration_micros,
start, end, limit, raw_traces). Both time bounds are always sent
(default: the last hour); limit (default 20) caps the number of traces. No match
returns [].
from_env
classmethod
¶
Standalone query client from GROW_JAEGER_* / JAEGER_QUERY_URL.
get_dependencies ¶
get_dependencies(end_ts: datetime | None = None, lookback_s: float | timedelta | None = None, *, start: datetime | None = None, end: datetime | None = None, service: str | None = None, cancel: CancelToken | None = None) -> list[DependencyLink]
Service dependency edges: legacy GET /api/dependencies?endTs=&lookback=.
Either Jaeger's native end_ts + lookback_s (these win) or the category window
start/end. Defaults: end now, lookback 24 h. service keeps only the edges
that touch it. The memory store derives edges on the fly; Cassandra/Elasticsearch/
OpenSearch need the spark-dependencies job, so [] is normal there.
get_operations ¶
get_operations(service: str, *, span_kind: str | None = None, cancel: CancelToken | None = None) -> list[JaegerOperation]
Operations of a service with their span kind: GET /api/v3/operations.
span_kind (server, client, producer, consumer, internal,
case-insensitive) is sent lower-case. An empty service raises
:class:ValidationError without a request.
get_trace ¶
get_trace(trace_id: str, *, start: datetime | None = None, end: datetime | None = None, raw_traces: bool | None = None, cancel: CancelToken | None = None) -> Trace | None
One trace: GET /api/v3/traces/{id}, falling back to the legacy
GET /api/traces/{id} when the v3 route is missing. None when the trace does
not exist.
trace_id is 32 or 16 hex characters (16 is left-padded); anything else raises
:class:ValidationError without a request. start/end form the lookup window
(a storage hint; default: the 7 days before now).
list_operations ¶
list_operations(service: str, *, span_kind: str | None = None, cancel: CancelToken | None = None) -> list[str]
Operation names of a service, de-duplicated across span kinds and sorted.
list_services ¶
Service names that reported spans: GET /api/v3/services (sorted).
require_trace ¶
require_trace(trace_id: str, *, start: datetime | None = None, end: datetime | None = None, raw_traces: bool | None = None, cancel: CancelToken | None = None) -> Trace
Like :meth:get_trace but raises :class:NotFoundError for a missing trace.
search_traces ¶
search_traces(query: TraceSearchQuery | None = None, *, cancel: CancelToken | None = None, **filters: Any) -> list[TraceSummary]
Trace summaries: GET /api/v3/trace-summaries (same filter as
:meth:find_traces).
JaegerRemoteSampler ¶
Bases: Sampler
OpenTelemetry sampler driven by Jaeger's remote sampling endpoint.
Rule (the same in every language): a per-operation strategy wins for a listed operation
(span name); every other operation uses the service-level rateLimitingSampling when
present, else probabilisticSampling (else defaultSamplingProbability).
Probabilistic decisions are deterministic per trace id. Until the first strategy
arrives, initial_sampling_rate applies; a failed or malformed poll keeps the last good
strategy.
Polling runs on a daemon thread (first fetch immediately) until :meth:close. Use the
sampler as the root of a ParentBased sampler (what init_tracing(remote_sampler=…)
does).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sampling_url
|
str | None
|
the endpoint ( |
required |
service
|
str
|
the service whose strategy is fetched ( |
required |
poll_interval_s
|
float | timedelta
|
seconds (or |
DEFAULT_SAMPLING_POLL_INTERVAL_S
|
initial_sampling_rate
|
float
|
probability until the first strategy arrives; default 0.001. |
DEFAULT_INITIAL_SAMPLING_RATE
|
config
|
JaegerConfig | None
|
transport settings (timeouts, retries, TLS, proxy, headers, token); default
:meth: |
None
|
auto_start
|
bool
|
start polling at once (default |
True
|
on_error
|
Callable[[BaseException], None] | None
|
called with the error when a poll fails. |
None
|
on_update
|
Callable[[JaegerSamplingStrategy], None] | None
|
called with the strategy after each successful poll. |
None
|
strategy
property
¶
The strategy in use, None before the first successful poll.
ready ¶
Wait until the first poll since :meth:start finished (successfully or not).
refresh ¶
Fetch the strategy once and install it; raises on failure (the previous strategy stays in use).
should_sample ¶
should_sample(parent_context: Context | None, trace_id: int, name: str, kind: SpanKind | None = None, attributes: Attributes = None, links: Sequence[Link] | None = None, trace_state: TraceState | None = None) -> SamplingResult
The decision for a new span (see the class description for the rule).
start ¶
Start polling (first fetch immediately). Idempotent; no-op after :meth:close.
JaegerSamplingStrategy
dataclass
¶
A sampling strategy as served by Jaeger, normalized.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
str
|
|
sampling_rate |
float | None
|
service-level |
max_traces_per_second |
float | None
|
service-level |
default_sampling_probability |
float | None
|
|
default_lower_bound_traces_per_second |
float | None
|
|
operations |
Sequence[OperationStrategy]
|
per-operation probabilistic rates. |
operation_rate ¶
Rate of a listed operation, None when the operation has no own strategy.
JaegerTraceQuery
dataclass
¶
JaegerTracingConfig
dataclass
¶
Bases: TracingConfig
:class:TracingConfig plus the Jaeger remote sampler (remote_sampler).
When remote_sampler is set it replaces sampler/sampler_ratio.
JaegerTracingHandle ¶
Bases: TracingHandle
A running Jaeger tracing setup: :class:TracingHandle plus endpoint and the
remote_sampler in use. :meth:shutdown also closes a sampler the handle created.
shutdown ¶
Flush and stop the provider (and an owned remote sampler); idempotent.
LoggerLike ¶
Bases: Protocol
Structured logger interface accepted in configuration (SPEC Logger).
NotFoundError ¶
Bases: JaegerError
Missing record (HTTP 404).
OperationStrategy
dataclass
¶
A per-operation probabilistic rate (operationSampling.perOperationStrategies).
PermissionDeniedError ¶
Bases: JaegerError
Authenticated but not allowed (HTTP 403).
RateLimitError ¶
Bases: JaegerError
Too many requests (HTTP 429); retry_after holds the requested delay when known.
RateLimiter ¶
Token bucket with Jaeger semantics: the balance starts full at max(1, rate) credits.
RemoteSamplerOptions
dataclass
¶
How init_tracing builds a :class:JaegerRemoteSampler (owned by the handle).
service_name defaults to the tracing service_name; sampling_url and the
transport settings to config (default :meth:JaegerConfig.from_env). With
parent_based (default) the remote sampler is the root of a ParentBased sampler.
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.
SamplingPreset
dataclass
¶
Secret ¶
Wraps a credential so it never shows up in str/repr/logs.
s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')
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).
TimeoutError ¶
Bases: JaegerError
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: JaegerError
Network error or server unavailable (HTTP 500, 502, 503).
UnsupportedError ¶
Bases: JaegerError
The service or deployment does not offer this capability (HTTP 501, missing API).
ValidationError ¶
Bases: JaegerError
Bad input (HTTP 400, 413, 422, other 4xx, client-side validation).
add_event ¶
Add an event to the active span (no-op without one).
any_value ¶
Python value of one OTLP/JSON AnyValue (None when empty or unknown).
intValue (sent as a string) becomes int, arrayValue a list and kvlistValue
a dict.
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_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.
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_id ¶
32-char lower-hex trace id of the active span, or None.
datetime_to_micros ¶
Microseconds since the epoch (naive datetimes are UTC).
default_tracer ¶
Tracer of this package from the global provider.
dependencies_from_body ¶
Dependency links from a legacy /api/dependencies body ({"data": [...]}).
dependencies_from_spans ¶
Service dependency links (parent service → child service, different services only).
error_for_code ¶
Return the error class for a code (ErrorCode member or wire value).
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).
get_logger ¶
The package logger (LOGGER_NAME), silent by default (NullHandler).
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_tracing ¶
init_tracing(config: TracingConfig | 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, sampler_config: JaegerConfig | None = None, **overrides: Any) -> JaegerTracingHandle
Set up OpenTelemetry tracing for Jaeger (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 / :class:JaegerTracingConfig
and/or its fields as keywords (service_name="checkout"). The environment fills every
field left unset (see :func:tracing_config_from_env; env defaults to
os.environ, env=False ignores it). With remote_sampler the Jaeger remote
strategy decides sampling (as the root of a ParentBased sampler unless
parent_based=False). A remote sampler created here takes its sampling_url, token
and transport settings from sampler_config (default :meth:JaegerConfig.from_env
over the same environment; :meth:JaegerClient.init_tracing passes the client's config).
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.
jaeger_exporter_factory ¶
The OTLP span exporter for a config (the exporter factory of init_tracing_with).
http/protobuf → opentelemetry-exporter-otlp-proto-http; grpc →
opentelemetry-exporter-otlp-proto-grpc (extra grow-jaeger[grpc]). Headers,
compression, export timeout and TLS come from the config. native raises
:class:ConfigError (Jaeger ingests OTLP).
key_values ¶
Attribute map from an OTLP/JSON KeyValue[] list (empty values are skipped).
legacy_to_traces ¶
Traces from the legacy /api/traces/{id} body ({"data": [{traceID, spans, …}]}).
Parent = first CHILD_OF reference in the same trace (else the first such reference);
other references become links. span.kind, otel.status_code/_description and
error tags become the kind and status; logs become events (event field = name).
mark_span_error ¶
Set ERROR status on span and record the exception (when error is one).
micros_to_datetime ¶
Exact UTC datetime for microseconds since the epoch.
nanos_to_micros ¶
Epoch microseconds from an OTLP nanosecond timestamp (decimal string or number).
Uses integer arithmetic; a missing or malformed value gives 0.
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.
otlp_span_to_span ¶
One OTLP/JSON span (with the service name of its resource) as a normalized span.
otlp_to_traces ¶
Traces from an OTLP/JSON TracesData ({"resourceSpans": [...]}).
Spans are grouped by trace id in order of first appearance and sorted per SPEC §5.
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_retry_after ¶
Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.
parse_sampling_strategy ¶
Parse a /sampling?service= response.
Missing numbers default to 0 (proto3 JSON), a missing strategyType means
PROBABILISTIC. Raises :class:ValidationError for a malformed body, a rate outside 0..1
or a negative maxTracesPerSecond.
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.
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.
resolve_jaeger_endpoint ¶
Exporter URL for a protocol.
For http/protobuf an endpoint without a path (a base such as http://jaeger:4318)
gets /v1/traces; any other endpoint is used as-is. Without an endpoint: the Jaeger
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.
sampling_ratio ¶
parentbased_traceidratio preset; <= 0 → parentbased_always_off, >= 1 →
parentbased_always_on.
set_error ¶
Mark the active span as failed: ERROR status, plus an exception event for exceptions.
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.
summaries_from_body ¶
SPEC TraceSummary values from a /api/v3/trace-summaries body.
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_env ¶
tracing_config_from_env(config: TracingConfig | None = None, *, env: Mapping[str, str] | None = None, **overrides: Any) -> JaegerTracingConfig
A :class:JaegerTracingConfig from the environment beneath config/overrides.
A field of config counts as explicit when it differs from the field default; keyword
overrides (any :class:JaegerTracingConfig field) are always explicit. Per field:
explicit > GROW_JAEGER_OTLP_* > OTEL_EXPORTER_OTLP_TRACES_* >
OTEL_EXPORTER_OTLP_* > Jaeger default.
============================ ====================================================
Field Variables
============================ ====================================================
protocol …_PROTOCOL (grpc, http/protobuf)
endpoint GROW_JAEGER_OTLP_GRPC_ENDPOINT /
GROW_JAEGER_OTLP_HTTP_ENDPOINT (by protocol),
GROW_JAEGER_OTLP_ENDPOINT,
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT (as-is),
OTEL_EXPORTER_OTLP_ENDPOINT (base; HTTP appends
/v1/traces)
headers …_HEADERS (k=v,k2=v2, percent-decoded)
compression …_COMPRESSION (gzip, none)
batch.export_timeout_s …_TIMEOUT (milliseconds or 10s)
tls …_CERTIFICATE (also GROW_JAEGER_OTLP_CA_CERT),
…_CLIENT_CERTIFICATE, …_CLIENT_KEY (paths)
service_name GROW_JAEGER_SERVICE_NAME, OTEL_SERVICE_NAME,
service.name in OTEL_RESOURCE_ATTRIBUTES
resource_attributes OTEL_RESOURCE_ATTRIBUTES (explicit keys win)
sampler/sampler_ratio OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG;
jaeger_remote / parentbased_jaeger_remote set
remote_sampler (arg endpoint=…,
pollingIntervalMs=…,initialSamplingRate=…)
propagators OTEL_PROPAGATORS
============================ ====================================================
env defaults to os.environ. A present but invalid value raises
:class:ConfigError naming the variable, never its value. The result is not validated
(init_tracing does that); service_name is "" when nothing sets it.
truncate ¶
Truncate text to limit characters (adds an ellipsis when cut).
user_agent ¶
grow-codes-<key>/<version> (python) plus <suffix> when given.
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).