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 OpenObserve.
from grow_openobserve import OpenObserveClient, OpenObserveConfig client = OpenObserveClient.from_env() # doctest: +SKIP client.logs.ingest_json("app", [{"message": "hello"}]) # 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.
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).
AsyncOpenObserveAdmin ¶
Async :class:OpenObserveAdmin; same methods, awaited.
create_service_account
async
¶
create_service_account(email: str, *, first_name: str = '', last_name: str = '') -> ServiceAccountToken
See :meth:OpenObserveAdmin.create_service_account.
delete_service_account
async
¶
See :meth:OpenObserveAdmin.delete_service_account.
list_organizations
async
¶
See :meth:OpenObserveAdmin.list_organizations.
list_service_accounts
async
¶
See :meth:OpenObserveAdmin.list_service_accounts.
rotate_service_account_token
async
¶
See :meth:OpenObserveAdmin.rotate_service_account_token.
AsyncOpenObserveClient ¶
Asynchronous OpenObserve 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. Same modules as :class:OpenObserveClient.
aclose
async
¶
Flush log clients, stop background resources and close connections (idempotent).
from_env
classmethod
¶
See :meth:OpenObserveClient.from_env.
init_tracing ¶
See :meth:OpenObserveClient.init_tracing.
log_client ¶
log_client(stream: str | None = None, *, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True, protocol: LogProtocol = 'json') -> AsyncBatchingLogClient
See :meth:OpenObserveClient.log_client; must be called inside a running loop.
log_exporter ¶
See :meth:OpenObserveClient.log_exporter (async exporters).
log_query ¶
See :meth:OpenObserveClient.log_query.
trace_query ¶
See :meth:OpenObserveClient.trace_query.
AsyncOpenObserveLogExporter ¶
Async :class:OpenObserveLogExporter (an :class:AsyncLogExporter).
AsyncOpenObserveLogQuery ¶
Bases: AsyncBaseLogQueryClient
Async :class:OpenObserveLogQuery; same methods, awaited.
search
async
¶
search(query: str, *, start: datetime | None = None, end: datetime | None = None, limit: int = 100, order: SearchOrder = 'desc', cursor: str | None = None, track_total_hits: bool = False) -> LogSearchResult
See :meth:OpenObserveLogQuery.search.
tail
async
¶
tail(query: str, on_record: Callable[[LogRecord], None], *, interval_s: float | timedelta = 1.0, start: Timestamp | None = None, on_error: Callable[[Exception], None] | None = None) -> AsyncTailHandle
See :meth:OpenObserveLogQuery.tail.
wait_for_log
async
¶
wait_for_log(query: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, predicate: RecordPredicate | None = None) -> LogRecord
See :meth:OpenObserveLogQuery.wait_for_log.
AsyncOpenObserveLogs ¶
Async :class:OpenObserveLogs (AsyncOpenObserveClient.logs); same methods, awaited.
histogram
async
¶
histogram(stream: str, *, start: Timestamp | None = None, end: Timestamp | None = None, interval: str | None = None, filter: str | None = None, stream_type: StreamType = 'logs') -> Histogram
See :meth:OpenObserveLogs.histogram.
ingest_bulk
async
¶
See :meth:OpenObserveLogs.ingest_bulk.
ingest_json
async
¶
ingest_json(stream: str, records: Sequence[Mapping[str, Any]] | Mapping[str, Any], *, gzip: bool = False) -> IngestResult
See :meth:OpenObserveLogs.ingest_json.
ingest_multi
async
¶
ingest_multi(stream: str, ndjson: str | bytes | Sequence[Mapping[str, Any]], *, gzip: bool = False) -> IngestResult
See :meth:OpenObserveLogs.ingest_multi.
ingest_otlp
async
¶
ingest_otlp(records: Sequence[LogRecord], *, stream: str | None = None, gzip: bool = False) -> OtlpIngestResult
See :meth:OpenObserveLogs.ingest_otlp.
search
async
¶
search(sql: str, *, start: Timestamp | None = None, end: Timestamp | None = None, from_: int = 0, size: int = 100, track_total_hits: bool = False, stream_type: StreamType = 'logs') -> SearchResult
See :meth:OpenObserveLogs.search.
search_around
async
¶
search_around(stream: str, timestamp: Timestamp, *, size: int = 10, sql: str | None = None, stream_type: StreamType = 'logs') -> SearchResult
See :meth:OpenObserveLogs.search_around.
tail ¶
tail(stream: str, on_row: Callable[[JsonRow], None], *, filter: str | None = None, start: Timestamp | None = None, interval_s: float | timedelta = 1.0, overlap_s: float | timedelta = 1.0, page_size: int = 1000, on_error: Callable[[Exception], None] | None = None, stream_type: StreamType = 'logs') -> AsyncRowTail
See :meth:OpenObserveLogs.tail; must be called inside a running event loop.
values_of
async
¶
values_of(stream: str, fields: Sequence[str], *, start: Timestamp | None = None, end: Timestamp | None = None, size: int = 10, stream_type: StreamType = 'logs') -> list[FieldValues]
See :meth:OpenObserveLogs.values_of.
AsyncOpenObserveOtlpLogExporter ¶
Async :class:OpenObserveOtlpLogExporter.
AsyncOpenObserveStreams ¶
Async :class:OpenObserveStreams; same methods, awaited.
create_stream
async
¶
create_stream(stream: str, *, fields: Sequence[SchemaField] = (), retention_days: int = 0, partition_keys: Sequence[PartitionKeyInput] = (), full_text_search_keys: Sequence[str] = (), index_fields: Sequence[str] = (), bloom_filter_fields: Sequence[str] = (), stream_type: StreamType = 'logs') -> None
See :meth:OpenObserveStreams.create_stream.
delete_stream
async
¶
See :meth:OpenObserveStreams.delete_stream.
get_stream_schema
async
¶
See :meth:OpenObserveStreams.get_stream_schema.
list_streams
async
¶
list_streams(stream_type: StreamType = 'logs', *, keyword: str | None = None, offset: int | None = None, limit: int | None = None) -> list[StreamInfo]
See :meth:OpenObserveStreams.list_streams.
update_stream_settings
async
¶
update_stream_settings(stream: str, *, retention_days: int | None = None, partition_keys: ListUpdate | None = None, full_text_search_keys: ListUpdate | None = None, index_fields: ListUpdate | None = None, bloom_filter_fields: ListUpdate | None = None, stream_type: StreamType = 'logs') -> None
See :meth:OpenObserveStreams.update_stream_settings.
AsyncOpenObserveTraceQuery ¶
Bases: AsyncBaseTraceQueryClient
Async :class:OpenObserveTraceQuery; same methods, awaited.
get_dependencies
async
¶
Always :class:UnsupportedError (enterprise-only service graph).
get_trace
async
¶
get_trace(trace_id: str, *, start: Timestamp | None = None, end: Timestamp | None = None) -> Trace | None
See :meth:OpenObserveTraceQuery.get_trace.
list_operations
async
¶
list_operations(service: str, *, start: Timestamp | None = None, end: Timestamp | None = None) -> list[str]
See :meth:OpenObserveTraceQuery.list_operations.
list_services
async
¶
See :meth:OpenObserveTraceQuery.list_services.
search_traces
async
¶
See :meth:OpenObserveTraceQuery.search_traces.
trace_time_range
async
¶
See :meth:OpenObserveTraceQuery.trace_time_range.
AsyncPollingTail ¶
Async :class:PollingTail; the polling task runs on the current event loop.
AsyncRowTail ¶
A running AsyncOpenObserveLogs.tail (asyncio task). :meth:stop is idempotent.
AsyncTraceQueryClient ¶
Bases: Protocol
Asynchronous trace query API (same methods, awaited).
AuthenticationError ¶
Bases: OpenObserveError
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.
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.
BulkAction
dataclass
¶
One _bulk action. Only index and create are accepted (the server ignores
delete/update, so the SDK rejects them with :class:ValidationError).
BulkItem
dataclass
¶
Outcome of one bulk action (status 200 = created).
BulkResult
dataclass
¶
Result of ingest_bulk. Always check errors: item failures keep HTTP 200.
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: OpenObserveError, 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: OpenObserveError
Invalid or missing configuration.
ConflictError ¶
Bases: OpenObserveError
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).
FieldValues
dataclass
¶
Distinct values of one field, most frequent first.
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").
IngestResult
dataclass
¶
Result of ingest_json / ingest_multi.
OpenObserve answers HTTP 200 even when some records were rejected: check failed.
ListDelta
dataclass
¶
An explicit add/remove change of a list setting (sent as given).
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).
NotFoundError ¶
Bases: OpenObserveError
Missing record (HTTP 404).
OpenObserveAdmin ¶
Admin helpers (client.admin). Every method accepts cancel=.
OSS OpenObserve has no RBAC: every service account can ingest, query and administer.
create_service_account ¶
create_service_account(email: str, *, first_name: str = '', last_name: str = '', cancel: CancelToken | None = None) -> ServiceAccountToken
Create a service account and return its token (POST /api/{org}/service_accounts).
:class:ConflictError when it already exists, :class:ValidationError for an invalid
e-mail.
delete_service_account ¶
Remove a service account (DELETE /api/{org}/service_accounts/{email});
:class:NotFoundError when it does not exist.
get_passcode ¶
The caller's ingest-only passcode (GET /api/{org}/passcode).
list_organizations ¶
Organizations visible to the caller (GET /api/organizations), including the
internal _meta organization.
list_service_accounts ¶
The organization's service accounts (GET /api/{org}/service_accounts).
rotate_service_account_token ¶
rotate_service_account_token(email: str, *, cancel: CancelToken | None = None) -> ServiceAccountToken
Issue a new token; the old one stops working at once
(PUT /api/{org}/service_accounts/{email}?rotateToken=true).
OpenObserveClient ¶
Synchronous OpenObserve 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.
Modules: :attr:logs (ingest + SQL search), :attr:streams, :attr:traces (trace query
on the configured traces stream) and :attr:admin.
close ¶
Flush log clients, stop background resources and close connections (idempotent).
from_env
classmethod
¶
Build a client from the GROW_OPENOBSERVE_* and OPENOBSERVE_* variables.
health ¶
Unauthenticated health check (GET /healthz); never raises for an unhealthy or
unreachable service (only :class:CancelledError and :class:ConfigError).
init_tracing ¶
:func:~grow_openobserve.init_tracing with this client's connection settings.
log_client ¶
log_client(stream: str | None = None, *, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True, protocol: LogProtocol = 'json') -> BatchingLogClient
A batching :class:LogClient that ships records to stream.
Records get resource (e.g. service.name), default redaction and trace
correlation from the active OpenTelemetry span. :meth:close of this client also
closes the log clients it created.
log_exporter ¶
A :class:LogExporter writing to stream (default: the config's stream):
protocol="json" (_json ingestion, default) or "otlp" (OTLP/JSON to
/v1/logs).
log_query ¶
The :class:LogQueryClient for stream (default: the config's stream).
ping ¶
Authenticated round trip (GET /api/{org}/config); returns the latency in ms.
:class:AuthenticationError on bad or missing credentials.
request ¶
Send a raw request through the client's transport (retries, hooks, redaction).
No auth header is added: build req.headers with :meth:OpenObserveConfig.authorization.
server_version ¶
The server version (version of GET /api/{org}/config, e.g. v1.1.2).
trace_query ¶
The :class:TraceQueryClient for stream (default: the config's
traces_stream).
OpenObserveConfig
dataclass
¶
Bases: BaseConfig
Immutable settings for :class:~grow_openobserve.OpenObserveClient.
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.
OpenObserve only accepts HTTP Basic auth: user + password (a root or normal user)
or user + token (a service-account e-mail and its token). A token that starts
with Basic is a pre-encoded header and is sent verbatim (no user needed).
password and token accept a str and are stored as :class:Secret; repr()
never shows them.
Environment (from_env): GROW_OPENOBSERVE_<NAME> first, then OPENOBSERVE_<NAME>
for URL, ORG, USER, PASSWORD, TOKEN, STREAM, TRACES_STREAM;
GROW_OPENOBSERVE_ only for CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT,
MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY,
PROXY.
authorization ¶
The Authorization header value (Basic …) or None without credentials.
The result is a credential: never log it.
from_env
classmethod
¶
Build from the environment, then validate.
Precedence: explicit keyword > GROW_OPENOBSERVE_<NAME> > OPENOBSERVE_<NAME> >
default. An explicit password drops a token found in the environment and vice
versa, so overriding the credential kind never trips the "password and token" rule.
env defaults to os.environ; pass a dict in tests.
known_secrets ¶
Credential values (and the encoded Basic header) to redact from errors and logs.
OpenObserveLogExporter ¶
:class:LogExporter that writes records with _json ingestion into one stream
(per-stream counters give exact accepted/rejected numbers).
OpenObserveLogQuery ¶
Bases: BaseLogQueryClient
:class:LogQueryClient on one stream (default: the config's stream).
A query that starts with SELECT is raw SQL; any other text becomes
match_all('<text>') (full-text search over the stream's full-text keys,
case-insensitive) on :attr:stream. The cursor is a row offset. Use
client.log_query(stream).
search ¶
search(query: str, *, start: datetime | None = None, end: datetime | None = None, limit: int = 100, order: SearchOrder = 'desc', cursor: str | None = None, track_total_hits: bool = False) -> LogSearchResult
One page of records; default window: the last 15 minutes, newest first, 100 rows.
track_total_hits fills total with the exact number of matches (one extra
request; DECISIONS 3).
tail ¶
tail(query: str, on_record: Callable[[LogRecord], None], *, interval_s: float | timedelta = 1.0, start: Timestamp | None = None, on_error: Callable[[Exception], None] | None = None) -> TailHandle
Follow new records. Text queries use the cursor-based logs.tail on
:attr:stream; raw SQL uses the generic polling tail on top of :meth:search.
wait_for_log ¶
wait_for_log(query: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, predicate: RecordPredicate | None = None) -> LogRecord
Poll :meth:search until a record (matching predicate) shows up; a stream that
does not exist yet counts as "no record yet". :class:TimeoutError otherwise.
OpenObserveLogs ¶
Logs ingestion and SQL search (client.logs).
Times are aware datetime objects (naive = UTC) or int epoch microseconds
(exact row timestamps); the SDK converts them to the server's microseconds itself.
Every method accepts cancel= (a :class:CancelToken).
histogram ¶
histogram(stream: str, *, start: Timestamp | None = None, end: Timestamp | None = None, interval: str | None = None, filter: str | None = None, stream_type: StreamType = 'logs', cancel: CancelToken | None = None) -> Histogram
Record counts per time bucket (histogram(_timestamp, …) via _search).
interval looks like "1 minute" (default: chosen by the server); filter is a
SQL WHERE condition such as level = 'error'.
ingest_bulk ¶
ingest_bulk(actions: Sequence[BulkAction] | str, *, gzip: bool = False, cancel: CancelToken | None = None) -> BulkResult
Elasticsearch-compatible bulk write: POST /api/{org}/_bulk.
Accepts :class:BulkAction objects or a raw NDJSON body. delete and update
actions raise :class:ValidationError (the server silently ignores them).
ingest_json ¶
ingest_json(stream: str, records: Sequence[Mapping[str, Any]] | Mapping[str, Any], *, gzip: bool = False, cancel: CancelToken | None = None) -> IngestResult
Write records with POST /api/{org}/{stream}/_json.
Give _timestamp in epoch µs (ms, ns and RFC 3339 are detected by the server);
without it the server uses its own time. Nested objects are flattened with _ by
the server. Partial failures keep HTTP 200: check :attr:IngestResult.failed.
ingest_multi ¶
ingest_multi(stream: str, ndjson: str | bytes | Sequence[Mapping[str, Any]], *, gzip: bool = False, cancel: CancelToken | None = None) -> IngestResult
Write newline-delimited JSON with POST /api/{org}/{stream}/_multi.
ndjson is the raw body or a list of objects. One bad line rejects the whole
request (:class:ValidationError).
ingest_otlp ¶
ingest_otlp(records: Sequence[LogRecord], *, stream: str | None = None, gzip: bool = False, cancel: CancelToken | None = None) -> OtlpIngestResult
Write SDK log records as OTLP/JSON (POST /api/{org}/v1/logs, header
stream-name; default: the configured stream). Trace flags are not stored.
search ¶
search(sql: str, *, start: Timestamp | None = None, end: Timestamp | None = None, from_: int = 0, size: int = 100, track_total_hits: bool = False, stream_type: StreamType = 'logs', cancel: CancelToken | None = None) -> SearchResult
Run a SQL query: POST /api/{org}/_search?type=logs.
Quote stream names with double quotes (SELECT * FROM "default"); without
ORDER BY rows come newest first; a SQL LIMIT overrides size. start
defaults to end - 15 minutes, end to now. track_total_hits fetches the exact
number of matching rows with one extra request into :attr:SearchResult.total_hits.
search_around ¶
search_around(stream: str, timestamp: Timestamp, *, size: int = 10, sql: str | None = None, stream_type: StreamType = 'logs', cancel: CancelToken | None = None) -> SearchResult
Rows around one timestamp: GET /api/{org}/{stream}/_around.
The anchor is a datetime or a row's exact _timestamp (µs); the anchor row is
included. sql is an optional SELECT … filter sent base64url-encoded; OpenObserve
v1.1.2 accepts it but does not apply it (verified), so filter the rows yourself.
tail ¶
tail(stream: str, on_row: Callable[[JsonRow], None], *, filter: str | None = None, start: Timestamp | None = None, interval_s: float | timedelta = 1.0, overlap_s: float | timedelta = 1.0, page_size: int = 1000, on_error: Callable[[Exception], None] | None = None, stream_type: StreamType = 'logs') -> RowTail
Follow a stream by polling _search with a _timestamp cursor.
OpenObserve has no live tail. Every poll re-reads overlap_s before the cursor and
drops rows it already delivered (full-row equality), so rows that are exact duplicates
within that window are delivered once. start defaults to now; errors go to
on_error and polling continues. Call :meth:RowTail.stop to end it.
values_of ¶
values_of(stream: str, fields: Sequence[str], *, start: Timestamp | None = None, end: Timestamp | None = None, size: int = 10, stream_type: StreamType = 'logs', cancel: CancelToken | None = None) -> list[FieldValues]
Distinct values with counts: GET /api/{org}/{stream}/_values?fields=a,b
(size values per field, most frequent first; default window: last 15 minutes).
OpenObserveOtlpLogExporter ¶
:class:LogExporter that writes records as OTLP/JSON to /api/{org}/v1/logs with
the stream-name header.
OpenObserveStreams ¶
Stream management (client.streams). Every method accepts cancel=.
create_stream ¶
create_stream(stream: str, *, fields: Sequence[SchemaField] = (), retention_days: int = 0, partition_keys: Sequence[PartitionKeyInput] = (), full_text_search_keys: Sequence[str] = (), index_fields: Sequence[str] = (), bloom_filter_fields: Sequence[str] = (), stream_type: StreamType = 'logs', cancel: CancelToken | None = None) -> None
Create a stream with an optional schema and settings: POST /api/{org}/streams/{s}.
delete_stream ¶
delete_stream(stream: str, *, stream_type: StreamType = 'logs', cancel: CancelToken | None = None) -> None
Delete a stream and its data: DELETE /api/{org}/streams/{stream} (alerts and
dashboards are kept). :class:NotFoundError when missing.
get_stream_schema ¶
get_stream_schema(stream: str, *, stream_type: StreamType = 'logs', cancel: CancelToken | None = None) -> StreamInfo
Schema, stats and settings of one stream; :class:NotFoundError when missing.
list_streams ¶
list_streams(stream_type: StreamType = 'logs', *, keyword: str | None = None, offset: int | None = None, limit: int | None = None, cancel: CancelToken | None = None) -> list[StreamInfo]
Streams of one type, sorted by name: GET /api/{org}/streams?type=….
keyword keeps only names containing that text; offset/limit page the list.
update_stream_settings ¶
update_stream_settings(stream: str, *, retention_days: int | None = None, partition_keys: ListUpdate | None = None, full_text_search_keys: ListUpdate | None = None, index_fields: ListUpdate | None = None, bloom_filter_fields: ListUpdate | None = None, stream_type: StreamType = 'logs', cancel: CancelToken | None = None) -> None
Change stream settings: PUT /api/{org}/streams/{stream}/settings.
A list replaces the current list (the SDK reads the schema and sends add/remove
deltas, one extra request); a :class:ListDelta is sent as given. Omitted settings stay
unchanged. Partition keys are field names (type value) or :class:PartitionKey.
:class:NotFoundError when the stream is missing.
OpenObserveTraceQuery ¶
Bases: BaseTraceQueryClient
:class:TraceQueryClient on one traces stream (default: the config's traces_stream).
search_traces uses traces/latest; with a filter each summary covers only the
matching spans (start, duration and span count), which keeps the call cheap.
get_dependencies raises :class:UnsupportedError: the service graph is an enterprise
feature (404 in the OSS server). Use client.traces or client.trace_query(stream).
get_dependencies ¶
Always :class:UnsupportedError (enterprise-only service graph).
get_trace ¶
get_trace(trace_id: str, *, start: Timestamp | None = None, end: Timestamp | None = None, cancel: CancelToken | None = None) -> Trace | None
All spans of a trace (traces/{id}/details, paginated), or None when the trace
(or the stream) does not exist in the window (default: the last 7 days).
list_operations ¶
list_operations(service: str, *, start: Timestamp | None = None, end: Timestamp | None = None, cancel: CancelToken | None = None) -> list[str]
Distinct operation names of one service in the window (default: 24 hours), sorted.
list_services ¶
list_services(*, start: Timestamp | None = None, end: Timestamp | None = None, cancel: CancelToken | None = None) -> list[str]
Distinct service_name values in the window (default: the last 24 hours), sorted.
search_traces ¶
search_traces(query: TraceSearchQuery | None = None, *, cancel: CancelToken | None = None) -> list[TraceSummary]
Recent traces matching query (traces/latest); default window: the last hour.
trace_time_range ¶
Where and when a trace was stored (traces/time_range, the server's trace index).
Organization
dataclass
¶
An OpenObserve organization (type is default or custom).
OtlpIngestResult
dataclass
¶
Result of ingest_otlp.
PartitionKey
dataclass
¶
A partition key; removed keys stay listed with disabled=True.
Passcode
dataclass
¶
The caller's ingest-only credential: Basic user:passcode may ingest but not search
or administer.
PermissionDeniedError ¶
Bases: OpenObserveError
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: OpenObserveError
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.
RowTail ¶
SchemaField
dataclass
¶
One schema field; type is the Arrow type name (Utf8, Int64, …).
SearchResult
dataclass
¶
Result of search and search_around.
Secret ¶
Wraps a credential so it never shows up in str/repr/logs.
s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')
ServiceAccount
dataclass
¶
A listed service account (the server masks its token, so none is returned).
ServiceAccountToken
dataclass
¶
A service account with its usable token.
Only create_service_account and rotate_service_account_token return the token; use
it as OpenObserveConfig(user=email, token=token).
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).
StreamInfo
dataclass
¶
A stream with its stats, schema and settings.
StreamSettings
dataclass
¶
Selected stream settings; raw holds the full server object.
TimeoutError ¶
Bases: OpenObserveError
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
¶
TraceTimeRange
dataclass
¶
Result of trace_time_range: where and when a trace was stored.
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: OpenObserveError
Network error or server unavailable (HTTP 500, 502, 503).
UnsupportedError ¶
Bases: OpenObserveError
The service or deployment does not offer this capability (HTTP 501, missing API).
ValidationError ¶
Bases: OpenObserveError
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.
create_span_exporter ¶
The span exporter for a resolved config.
http/protobuf and native → OTLP/HTTP protobuf (the official exporter); grpc →
OTLP/gRPC (extra grpc) with authorization, organization and stream-name
metadata. TLS settings come from config.tls or else the OpenObserve config.
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).
default_tracer ¶
Tracer of this package from the global provider.
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).
format_timestamp ¶
RFC 3339 UTC form with microseconds and Z; naive datetimes are taken as UTC.
get_logger ¶
The package logger (LOGGER_NAME), silent by default (NullHandler).
grpc_endpoint ¶
The default OTLP/gRPC endpoint: the URL's host with port 5081 (when it uses 5080 or none).
hit_to_summary ¶
Map one traces/latest hit to a :class:TraceSummary.
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, *, openobserve: OpenObserveConfig | None = None, stream: str | None = None, propagator_factories: Mapping[str, PropagatorFactory] | None = None, span_processors: Sequence[SpanProcessor] = (), id_generator: IdGenerator | None = None) -> TracingHandle
Set up OpenTelemetry tracing that exports to OpenObserve (SPEC §5).
Endpoint, auth and traces stream come from openobserve (default
OpenObserveConfig.from_env()) and stream (default: its traces_stream); the
caller's config.endpoint and config.headers override them. With protocol="grpc"
and no endpoint, the URL's host on port 5081 is used. 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.
is_sql_query ¶
True when query is raw SQL (starts with SELECT, case-insensitive).
log_record_to_row ¶
The row written by _json ingestion for record.
Flattened resource and attribute keys, plus _timestamp (µs), body, severity
(text), severity_number, trace_id, span_id and trace_flags. Record fields
win over attributes with the same column name; lists are stored as JSON strings.
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.
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_stream_name ¶
Server-side stream name normalization: lower case, every non [a-z0-9_] → _.
normalize_stream_name("Sdk-Mixed.x") 'sdk_mixed_x'
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.
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_timestamp ¶
Parse RFC 3339 (any fraction precision, Z/offset; none = UTC) to aware UTC.
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.
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.
row_to_log_record ¶
Normalize an OpenObserve row into a :class:LogRecord.
_timestamp (µs), body|message, severity|level (+ severity_number),
trace_id, span_id and trace_flags become record fields; well-known resource
columns (service_name, host_name, …) go to resource; every other non-null column
goes to attributes under its flattened server name.
row_to_span ¶
Map an OpenObserve span row to the normalized :class:Span.
start_time/end_time are nanoseconds, span_kind is a string number, events
and links are JSON strings. Internal columns (_timestamp, infer_service_*,
o2_db_*, …) are dropped; the rest become attributes under the server's flattened names.
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.
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.
text_query_sql ¶
SELECT * FROM "<stream>" WHERE match_all('<text>') ORDER BY _timestamp <order>;
an empty text matches every row.
to_attr_value ¶
Convert any Python value to an attribute value (unknown types become str(value)).
to_otlp_logs_request ¶
An OTLP/JSON ExportLogsServiceRequest (grouped by resource, scope
grow-codes-openobserve).
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.
trace_filter ¶
The traces/latest filter (a SQL WHERE fragment) for a search query.
Tag keys are flattened like the server stores them (db.system → db_system).
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).
traces_endpoint ¶
The OTLP/HTTP traces endpoint: <url>/api/{org}/v1/traces.
tracing_defaults ¶
Service defaults merged under the caller's :class:TracingConfig: OTLP/HTTP protobuf to
:func:traces_endpoint with authorization (Basic) and stream-name headers.
truncate ¶
Truncate text to limit characters (adds an ellipsis when cut).
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).