Skip to content

API reference

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

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

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

Python

Grow Codes SDK for SigNoz.

from grow_signoz import SignozClient, SignozConfig client = SignozClient.from_env() # doctest: +SKIP

AttrValue module-attribute

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

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

AggregateBuilder

Bases: _AggregateSpec

Fluent builder for SigNoz aggregations (requestType scalar or time_series).

client.query.aggregate("traces").count("calls").p99("duration_nano", "p99") .group_by("name").run(). Aliases are mapped back from SigNoz's __result_<i> columns by aggregation index. Default window: the last hour.

run

run() -> AggregateResult

Run a scalar query: one row per group.

time_series

time_series(step_s: int | None = None) -> list[AggregateSeries]

Run a time-series query with buckets of step_s seconds (default: SigNoz picks).

AggregatePoint dataclass

One point of a time series.

AggregateResult dataclass

Result of :meth:AggregateBuilder.run.

AggregateRow dataclass

One scalar result row.

AggregateSeries dataclass

One series of :meth:AggregateBuilder.time_series.

Aggregation dataclass

One aggregation: a SigNoz expression such as count() or p99(duration_nano).

ApiResult dataclass

Decoded payload (data of the envelope) and the envelope's warning messages.

AsyncAggregateBuilder

Bases: _AggregateSpec

Async :class:AggregateBuilder (await builder.run()).

run async

run() -> AggregateResult

Run a scalar query: one row per group.

time_series async

time_series(step_s: int | None = None) -> list[AggregateSeries]

Run a time-series query with buckets of step_s seconds.

AsyncBaseLogQueryClient

Async :class:BaseLogQueryClient.

AsyncBaseTraceQueryClient

Async :class:BaseTraceQueryClient.

query_trace_id

query_trace_id(trace_id: str) -> str

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

AsyncBatchProcessor

Bases: _BatchCore

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

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

add

add(record: LogRecord) -> bool

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

add_wait async

add_wait(record: LogRecord) -> bool

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

flush async

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

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

shutdown async

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

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

AsyncBatchingLogClient

Bases: _ClientBase

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

close async

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

Flush and shut down; idempotent.

send_wait async

send_wait(record: LogRecord | LogInput) -> bool

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

AsyncHttpTransport

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

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

aclose async

aclose() -> None

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

request async

request(req: Request) -> Response

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

AsyncLogClient

Bases: Protocol

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

AsyncLogExporter

Bases: Protocol

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

AsyncLogQueryClient

Bases: Protocol

Asynchronous query API (same methods, awaited).

AsyncPollingTail

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

AsyncSignozClient

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

Same surface as :class:SignozClient with awaited methods (:attr:query, :attr:traces, :attr:logs, :meth:log_client returns an :class:AsyncBatchingLogClient). Cancel a call by cancelling its task: the SDK raises :class:CancelledError, which is also an :class:asyncio.CancelledError.

resources property

resources: ResourceRegistry

Synchronous background resources stopped by :meth:aclose.

traces property

traces: AsyncSignozQueryClient

Tracing-category query client (the same object as :attr:query).

aclose async

aclose() -> None

Flush and close log clients, tracing handles and tails, then close connections.

Idempotent.

from_env classmethod

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

Build a client from GROW_SIGNOZ_* and vendor environment variables.

health async

health() -> HealthStatus

See :meth:SignozClient.health.

init_tracing

init_tracing(config: TracingConfig | str, **overrides: Any) -> TracingHandle

See :meth:SignozClient.init_tracing; shut down by :meth:aclose.

log_client

log_client(*, service_name: str | None = None, service_version: str | None = None, environment: str | None = None, protocol: OtlpProtocol | None = None, endpoint: str | None = None, headers: Mapping[str, str] | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: Any = _UNSET, correlate: bool = True) -> AsyncBatchingLogClient

An async OTLP log client (see :func:create_async_log_client), closed by :meth:aclose. Raises :class:CancelledError when the client is closed.

ping async

ping() -> float

See :meth:SignozClient.ping.

request async

request(req: Request) -> Response

Send a raw request through the client's transport.

server_version async

server_version() -> str

See :meth:SignozClient.server_version.

AsyncSignozLogExporter

Bases: _ExporterBase

AsyncLogExporter variant of :class:SignozLogExporter (gRPC runs in a thread).

export async

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

Send one batch; raises SDK errors for transport/HTTP failures.

shutdown async

shutdown() -> None

Close connections (idempotent).

AsyncSignozLogQueryClient

Bases: AsyncBaseLogQueryClient

Async :class:SignozLogQueryClient; get it from :attr:AsyncSignozClient.logs.

list_labels async

list_labels() -> list[str]

See :meth:SignozLogQueryClient.list_labels.

list_streams async

list_streams() -> list[str]

See :meth:SignozLogQueryClient.list_streams.

search async

search(query: str, *, start: datetime | None = None, end: datetime | None = None, limit: int = 100, order: SearchOrder = 'desc', cursor: str | None = None) -> LogSearchResult

See :meth:SignozLogQueryClient.search.

tail async

tail(query: str, on_record: Callable[[LogRecord], None], *, interval_s: float | timedelta = 1.0, start: datetime | None = None, on_error: Callable[[Exception], None] | None = None, reconnect_delay_s: float | timedelta | None = None) -> AsyncSignozTailHandle

See :meth:SignozLogQueryClient.tail (runs as a task on the current loop).

AsyncSignozQueryClient

Bases: AsyncBaseTraceQueryClient

Async :class:SignozQueryClient; get it from :attr:AsyncSignozClient.query.

aggregate

aggregate(signal: SignozSignal) -> AsyncAggregateBuilder

Start an async aggregation over logs or traces.

get_dependencies async

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

See :meth:SignozQueryClient.get_dependencies.

get_trace async

get_trace(trace_id: str) -> SignozTrace | None

See :meth:SignozQueryClient.get_trace.

list_field_values async

list_field_values(name: str, *, source: SignozSignal = 'logs', search: str | None = None) -> list[str | int | float | bool]

See :meth:SignozQueryClient.list_field_values.

list_log_fields async

list_log_fields(*, search: str | None = None, limit: int | None = None) -> list[LogField]

See :meth:SignozQueryClient.list_log_fields.

list_operations async

list_operations(service: str, *, start: datetime | None = None, end: datetime | None = None) -> list[str]

See :meth:SignozQueryClient.list_operations.

list_services async

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

See :meth:SignozQueryClient.list_services.

query_logs async

query_logs(filter: str | FilterBuilder | None = None, *, start: datetime | None = None, end: datetime | None = None, limit: int | None = None, order_by: SortOrder = 'desc', cursor: str | None = None, select_fields: Sequence[str] | None = None) -> LogQueryResult

See :meth:SignozQueryClient.query_logs.

query_range async

query_range(body: Mapping[str, Any], *, operation: str = 'query_range') -> ApiResult

Post a raw /api/v5/query_range body; returns data plus warnings.

query_traces async

query_traces(*, service: str | None = None, operation: str | None = None, filter: str | FilterBuilder | None = None, start: datetime | None = None, end: datetime | None = None, limit: int | None = None, offset: int = 0, order_by: SortOrder = 'desc') -> SpanQueryResult

See :meth:SignozQueryClient.query_traces.

search_traces async

search_traces(query: TraceSearchQuery | None = None, *, filter: str | FilterBuilder | None = None) -> list[TraceSummary]

See :meth:SignozQueryClient.search_traces.

AsyncSignozTailHandle

A running async live tail (task on the current event loop); await stop().

stop async

stop() -> None

Cancel the tail task and close its connection (idempotent).

AsyncTraceQueryClient

Bases: Protocol

Asynchronous trace query API (same methods, awaited).

AuthenticationError

Bases: SignozError

Credentials missing or rejected (HTTP 401).

BaseConfig dataclass

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

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

from_env classmethod

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

Build from the environment, then validate.

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

known_secrets

known_secrets() -> list[str]

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

validate

validate() -> _C

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

BaseLogQueryClient

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

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

BaseTraceQueryClient

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

query_trace_id

query_trace_id(trace_id: str) -> str

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

BatchOptions dataclass

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

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

from_mapping classmethod

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

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

BatchProcessor

Bases: _BatchCore

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

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

add

add(record: LogRecord) -> bool

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

flush

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

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

shutdown

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

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

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

BatchStats dataclass

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

BatchingLogClient

Bases: _ClientBase

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

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

close

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

Flush and shut down; idempotent.

CancelToken

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

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

cancel

cancel() -> None

Request cancellation (idempotent).

on_cancel

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

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

wait

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

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

CancelledError

Bases: SignozError, 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: SignozError

Invalid or missing configuration.

ConflictError

Bases: SignozError

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

EnvReader

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

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

duration

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

Duration in seconds.

lookup

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

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

ErrorCode

Bases: str, Enum

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

ErrorInfo dataclass

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

ExportResult dataclass

Outcome of one :meth:LogExporter.export call.

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

FilterBuilder

Immutable builder for SigNoz filter expressions.

FilterBuilder().eq("service.name", "x").in_("severity_text", ["WARN", "ERROR"]).build() → service.name = 'x' AND severity_text IN ('WARN', 'ERROR'). Clauses are joined with AND; use :meth:or_ / :meth:not_ for groups (rendered in parentheses). Every method returns a new builder; invalid field names, empty lists and non-finite numbers raise :class:ValidationError.

is_empty property

is_empty: bool

True when no clause was added.

build

build() -> str

The expression ("" when empty).

contains

contains(name: str, text: str) -> FilterBuilder

field CONTAINS 'text' — matches text literally (LIKE wildcards escaped).

create classmethod

create() -> FilterBuilder

A new empty builder.

eq

eq(name: str, value: FilterValue) -> FilterBuilder

field = value.

exists

exists(name: str) -> FilterBuilder

field EXISTS.

gt

gt(name: str, value: FilterValue) -> FilterBuilder

field > value.

gte

gte(name: str, value: FilterValue) -> FilterBuilder

field >= value.

in_

in_(name: str, values: Iterable[FilterValue]) -> FilterBuilder

field IN (v1, v2, …) (non-empty list).

like

like(name: str, pattern: str) -> FilterBuilder

field LIKE 'pattern' — % and _ are wildcards; passed as given.

lt

lt(name: str, value: FilterValue) -> FilterBuilder

field < value.

lte

lte(name: str, value: FilterValue) -> FilterBuilder

field <= value.

ne

ne(name: str, value: FilterValue) -> FilterBuilder

field != value.

not_

not_(expression: FilterBuilder | str) -> FilterBuilder

NOT (expression).

not_contains

not_contains(name: str, text: str) -> FilterBuilder

NOT field CONTAINS 'text' (literal match).

not_exists

not_exists(name: str) -> FilterBuilder

field NOT EXISTS.

not_in

not_in(name: str, values: Iterable[FilterValue]) -> FilterBuilder

field NOT IN (v1, v2, …) (non-empty list).

or_

or_(*alternatives: FilterBuilder | str) -> FilterBuilder

((a) OR (b) …) from builders/expressions; empty alternatives are ignored.

raw

raw(expression: str) -> FilterBuilder

A raw expression, passed through untouched (parenthesised when it contains OR).

regexp

regexp(name: str, pattern: str) -> FilterBuilder

field REGEXP 're'.

text

text(value: str) -> FilterBuilder

Full-text search of the log body: 'text'.

where

where(name: str, op: FilterOperator, value: FilterValue) -> FilterBuilder

field <op> value.

GroupByField dataclass

A group-by field with an optional context (resource/attribute/span/log).

HealthStatus dataclass

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

Hooks dataclass

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

HttpTransport

Synchronous transport (one per client).

Service options (all optional):

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

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

close

close() -> None

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

request

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

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

LogClient

Bases: Protocol

Synchronous log client (SPEC LogClient).

LogExporter

Bases: Protocol

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

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

LogField dataclass

A log field known to SigNoz (one entry per name and context).

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.

LogQueryResult dataclass

One page of :meth:SignozQueryClient.query_logs.

LogRecord dataclass

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

from_json classmethod

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

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

json_size

json_size() -> int

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

to_json

to_json() -> dict[str, Any]

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

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

to_json_str

to_json_str() -> str

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

LogSearchResult dataclass

One page of search results.

LogSink

Bases: Protocol

Anything that accepts records: every log client.

Logger

Small structured logger writing to a :class:LogSink.

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

child

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

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

LoggerLike

Bases: Protocol

Structured logger interface accepted in configuration (SPEC Logger).

NotFoundError

Bases: SignozError

Missing record (HTTP 404).

PermissionDeniedError

Bases: SignozError

Authenticated but not allowed (HTTP 403).

PollingTail

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

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

poll_once

poll_once() -> int

Run one poll; returns the number of delivered records.

RateLimitError

Bases: SignozError

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

RedactionProcessor

Returns redacted copies of records.

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

is_sensitive

is_sensitive(name: str) -> bool

True when an attribute name matches one of the keys.

process

process(record: LogRecord) -> LogRecord

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

redact_attributes

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

Redacted copy of an attribute mapping.

redact_text

redact_text(text: str) -> str

Apply every pattern to text.

Request dataclass

One logical API call (possibly several attempts).

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

RequestInfo dataclass

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

ResourceRegistry

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

register

register(item: Stoppable) -> None

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

Response dataclass

A completed HTTP response (body fully read).

json

json() -> Any

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

ResponseInfo dataclass

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

RetryPolicy dataclass

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

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

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

max_attempts property

max_attempts: int

Total attempts including the first one.

backoff

backoff(retry: int) -> float

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

backoff_cap

backoff_cap(retry: int) -> float

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

Secret

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

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

reveal

reveal() -> str

Return the wrapped value.

Severity

Bases: IntEnum

Log severity; the values are the OpenTelemetry severity numbers.

from_python_level classmethod

from_python_level(level: int) -> Severity

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

parse classmethod

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

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

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

SignozClient

Synchronous SigNoz client. Thread-safe; use as a context manager or call :meth:close.

  • :meth:health, :meth:ping, :meth:server_version
  • :attr:query — :class:SignozQueryClient (logs, spans, traces, services, aggregations); :attr:traces is the same object (TraceQueryClient)
  • :attr:logs — :class:SignozLogQueryClient (LogQueryClient: search, tail, …)
  • :meth:log_client — OTLP log client; :meth:init_tracing — OpenTelemetry tracing

:meth:close flushes and closes every log client, tracing handle and tail created through it. Every I/O method accepts cancel= (a :class:CancelToken).

resources property

resources: ResourceRegistry

Background resources (log clients, tracing handles, tails) stopped by :meth:close.

traces property

traces: SignozQueryClient

Tracing-category query client (the same object as :attr:query).

close

close() -> None

Flush and close log clients, tracing handles and tails, then close connections.

Idempotent.

from_env classmethod

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

Build a client from GROW_SIGNOZ_* and vendor environment variables.

health

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

Unauthenticated liveness (GET /api/v1/health?live=1, also checks ClickHouse).

Never raises for an unhealthy or unreachable service (only CancelledError and ConfigError).

init_tracing

init_tracing(config: TracingConfig | str, **overrides: Any) -> TracingHandle

Tracing to the collector with this client's config (see :func:init_tracing); the handle is shut down by :meth:close.

Raises :class:CancelledError when the client is closed.

log_client

log_client(*, service_name: str | None = None, service_version: str | None = None, environment: str | None = None, protocol: OtlpProtocol | None = None, endpoint: str | None = None, headers: Mapping[str, str] | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: Any = _UNSET, correlate: bool = True) -> BatchingLogClient

An OTLP log client for the collector (see :func:create_log_client); it is flushed and closed by :meth:close.

Raises :class:CancelledError when the client is closed.

ping

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

Authenticated round trip (GET /api/v1/fields/keys with SIGNOZ-API-KEY).

Returns the latency in milliseconds; :class:AuthenticationError on a bad key, :class:ConfigError without one.

request

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

Send a raw request through the client's transport (retries, hooks, redaction).

server_version

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

Server version from GET /api/v1/version (leading v stripped).

The official community image reports an empty version → :class:UnsupportedError.

SignozConfig dataclass

Bases: BaseConfig

Immutable settings for :class:~grow_signoz.SignozClient.

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. api_key and ingestion_key accept a str and are stored as :class:Secret; repr() never shows them.

Service fields:

  • api_key — query API key sent as SIGNOZ-API-KEY. Needed only for query calls and :meth:~grow_signoz.SignozClient.ping; an ingest-only client does not need it.
  • otlp_endpoint — collector endpoint (default http://127.0.0.1:4318 for http/protobuf, http://127.0.0.1:4317 for grpc).
  • otlp_protocol — "http/protobuf" (default) or "grpc".
  • ingestion_key — SigNoz Cloud ingestion key, sent as signoz-ingestion-key on every OTLP export (self-hosted collectors ignore it).

Environment (from_env): explicit keyword > GROW_SIGNOZ_<NAME> > vendor variable > default. URL (SIGNOZ_URL), API_KEY (SIGNOZ_API_KEY), OTLP_ENDPOINT (SIGNOZ_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_ENDPOINT), OTLP_PROTOCOL (OTEL_EXPORTER_OTLP_PROTOCOL), INGESTION_KEY (SIGNOZ_INGESTION_KEY), plus the common CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY, PROXY.

validate

validate() -> _C

Common checks plus SigNoz rules; raises :class:ConfigError.

with_changes

with_changes(**changes: Any) -> _C

Copy with some fields replaced (validated).

SignozLogExporter

Bases: _ExporterBase

LogExporter sending OTLP logs to the SigNoz collector.

HTTP/protobuf (POST {endpoint}/v1/logs, optional gzip) or gRPC (LogsService/Export, extra grow-signoz[grpc]). Adds signoz-ingestion-key for SigNoz Cloud when configured. Failed batches are retried by the :class:BatchProcessor.

export

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

Send one batch; raises SDK errors for transport/HTTP failures.

shutdown

shutdown() -> None

Close connections (idempotent).

SignozLogQueryClient

Bases: BaseLogQueryClient

LogQueryClient for SigNoz. query strings are SigNoz filter expressions; bare words are full-text searches of the log body. Get it from :attr:SignozClient.logs.

list_labels

list_labels() -> list[str]

Distinct log field names (attributes, resource attributes, intrinsic fields), sorted.

list_streams

list_streams() -> list[str]

Service names that sent logs (SigNoz has no streams; service.name is the equivalent), sorted.

search

search(query: str, *, start: datetime | None = None, end: datetime | None = None, limit: int = 100, order: SearchOrder = 'desc', cursor: str | None = None) -> LogSearchResult

Search logs (default window: the last hour, newest first, 100 per page).

tail

tail(query: str, on_record: Callable[[LogRecord], None], *, interval_s: float | timedelta = 1.0, start: datetime | None = None, on_error: Callable[[Exception], None] | None = None, reconnect_delay_s: float | timedelta | None = None) -> SignozTailHandle

Live tail over GET /api/v3/logs/livetail (server-sent events).

Calls on_record once per matching record from a background thread; reconnects after the stream ends (resuming at the last seen timestamp, de-duplicating by row id) after reconnect_delay_s (default interval_s). Authentication, permission, unsupported and config errors stop the tail after on_error. The client's close() stops it.

SignozLogRecord dataclass

Bases: LogRecord

A :class:LogRecord read from SigNoz, with the row id and the exact timestamp.

timestamp has microsecond precision (Python datetime); time_unix_nano keeps the exact epoch nanoseconds.

SignozQueryClient

Bases: BaseTraceQueryClient

Query client for SigNoz (SIGNOZ-API-KEY auth); implements TraceQueryClient.

Logs and spans via /api/v5/query_range, traces via the waterfall API, services and operations via v5 aggregations, dependencies via /api/v1/dependency_graph, log fields via /api/v1/fields/keys. Get it from :attr:SignozClient.query. Every method accepts cancel= (a :class:CancelToken).

aggregate

aggregate(signal: SignozSignal) -> AggregateBuilder

Start an aggregation (count / percentiles / …) over logs or traces.

get_dependencies

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

Service dependency edges in the window (default: the last hour), sorted.

Edges come from client→server spans and from client spans with db.system or messaging.system.

get_trace

get_trace(trace_id: str, *, cancel: CancelToken | None = None) -> SignozTrace | None

Full trace via POST /api/v4/traces/{id}/waterfall; None when unknown.

Span start times have millisecond precision. A trace larger than the server's waterfall window is completed with raw span queries.

list_field_values

list_field_values(name: str, *, source: SignozSignal = 'logs', search: str | None = None, cancel: CancelToken | None = None) -> list[str | int | float | bool]

Distinct values of a field for logs or traces, sorted.

list_log_fields

list_log_fields(*, search: str | None = None, limit: int | None = None, cancel: CancelToken | None = None) -> list[LogField]

Log fields, one entry per name and context, sorted by name then context.

list_operations

list_operations(service: str, *, start: datetime | None = None, end: datetime | None = None, cancel: CancelToken | None = None) -> list[str]

Span names of service in the window (default: the last hour), sorted.

list_services

list_services(*, start: datetime | None = None, end: datetime | None = None, cancel: CancelToken | None = None) -> list[str]

Every service with spans in the window (default: the last hour), sorted.

query_logs

query_logs(filter: str | FilterBuilder | None = None, *, start: datetime | None = None, end: datetime | None = None, limit: int | None = None, order_by: SortOrder = 'desc', cursor: str | None = None, select_fields: Sequence[str] | None = None, cancel: CancelToken | None = None) -> LogQueryResult

Raw log query: one page of records ordered by timestamp, ties by id.

filter is a SigNoz filter expression or :class:FilterBuilder (empty: every log; bare words search the body). Window default: the last hour (end exclusive). limit 1..10000 (None/0 → 100). Paging uses the SDK's own cursor, never the server's nextCursor (which skips rows in the millisecond before it): the next page repeats the boundary millisecond and excludes the ids already returned there.

query_range

query_range(body: Mapping[str, Any], *, operation: str = 'query_range', cancel: CancelToken | None = None) -> ApiResult

Post a raw /api/v5/query_range body; returns data plus warnings.

query_traces

query_traces(*, service: str | None = None, operation: str | None = None, filter: str | FilterBuilder | None = None, start: datetime | None = None, end: datetime | None = None, limit: int | None = None, offset: int = 0, order_by: SortOrder = 'desc', cancel: CancelToken | None = None) -> SpanQueryResult

Raw span query: one :class:Span per matching span (offset paging).

search_traces

search_traces(query: TraceSearchQuery | None = None, *, filter: str | FilterBuilder | None = None, cancel: CancelToken | None = None) -> list[TraceSummary]

Trace search, newest first (default 20): a trace matches when any span matches.

start_micros, span_count (all spans), root service and name come from each hit's waterfall (millisecond precision, 4 requests at a time); duration_micros is the root span's.

SignozTailHandle

A running live tail (daemon thread); :meth:stop is idempotent.

stopped property

stopped: bool

True after :meth:stop or a fatal error.

stop

stop() -> None

Stop the tail and close its connection (idempotent).

SignozTrace dataclass

Bases: Trace

A :class:Trace read from the SigNoz waterfall API.

Span dataclass

A finished span as returned by a query API.

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

from_json classmethod

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

Parse the wire form; ValidationError for malformed input.

to_json

to_json() -> dict[str, Any]

Normalized wire form (camelCase, schema Span).

SpanBatchOptions dataclass

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

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

SpanNode dataclass

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

find

find(name: str) -> SpanNode | None

Depth-first search for a node by span name.

SpanQueryResult dataclass

Result of :meth:SignozQueryClient.query_traces: one :class:Span per matching span.

SpanStatus dataclass

from_json classmethod

from_json(data: Any) -> SpanStatus

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

SseParser

Incremental text/event-stream parser: feed text, get (event, data) pairs.

TimeoutError

Bases: SignozError

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

TlsConfig dataclass

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

Trace dataclass

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

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

TraceQueryClient

Bases: Protocol

Synchronous trace query API.

TraceSearchQuery dataclass

matches

matches(trace: Trace) -> bool

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

TraceSummary dataclass

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

from_trace classmethod

from_trace(trace: Trace) -> TraceSummary

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

to_json

to_json() -> dict[str, Any]

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

TracingASGIMiddleware

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

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

TracingConfig dataclass

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

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

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

propagators_set property

propagators_set: bool

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

protocol_set property

protocol_set: bool

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

validate

validate() -> None

Raise ConfigError for invalid settings (never echoing values).

with_changes

with_changes(**changes: Any) -> TracingConfig

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

TracingHandle

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

force_flush

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

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

shutdown

shutdown() -> None

Flush and stop the provider and its exporter; idempotent.

tracer

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

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

TracingWSGIMiddleware

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

UnavailableError

Bases: SignozError

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

UnsupportedError

Bases: SignozError

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

ValidationError

Bases: SignozError

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

add_event

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

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

and_filters

and_filters(*parts: FilterBuilder | str | None) -> str

Join expressions with AND, parenthesising each non-empty part when there are several.

apoll_until async

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

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

async_httpx_event_hooks

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

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

async_wait_for_log async

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

Async form of :func:wait_for_log.

async_wait_for_trace async

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

Async form of :func:wait_for_trace.

build_propagator

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

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

build_resource

build_resource(config: TracingConfig) -> Resource

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

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

build_sampler

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

OpenTelemetry sampler for a TracingConfig.sampler name.

build_tree

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

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

create_async_log_client

create_async_log_client(config: SignozConfig | None = None, *, service_name: str | None = None, service_version: str | None = None, environment: str | None = None, protocol: OtlpProtocol | None = None, endpoint: str | None = None, headers: Mapping[str, str] | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: Any = _UNSET, correlate: bool = True, http_transport: AsyncBaseTransport | None = None) -> AsyncBatchingLogClient

Async :func:create_log_client (an :class:AsyncBatchingLogClient).

create_log_client

create_log_client(config: SignozConfig | None = None, *, service_name: str | None = None, service_version: str | None = None, environment: str | None = None, protocol: OtlpProtocol | None = None, endpoint: str | None = None, headers: Mapping[str, str] | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: Any = _UNSET, correlate: bool = True, http_transport: BaseTransport | None = None) -> BatchingLogClient

A :class:BatchingLogClient sending OTLP logs to the SigNoz collector.

Needs no API key (only ingestion_key for SigNoz Cloud). service_name (default unknown_service), service_version and environment become resource attributes; protocol/endpoint default to the config; options tunes the batch processor; redaction defaults to RedactionProcessor() (None disables it).

create_signoz_span_exporter

create_signoz_span_exporter(config: TracingConfig) -> SpanExporter

The span exporter for a config (the exporter factory of init_tracing_with).

http/protobuf → OTLP/HTTP protobuf to {endpoint}/v1/traces; grpc → OTLP/gRPC (extra grow-signoz[grpc]). native raises :class:ConfigError.

current_span

current_span() -> otel_trace.Span

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

current_span_id

current_span_id() -> str | None

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

current_trace_context

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

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

current_trace_id

current_trace_id() -> str | None

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

datetime_to_micros

datetime_to_micros(value: datetime) -> int

Microseconds since the epoch (naive datetimes are UTC).

default_tracer

default_tracer() -> otel_trace.Tracer

Tracer of this package from the global provider.

dependencies_from_spans

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

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

encode_logs

encode_logs(records: Sequence[LogRecord], scope_name: str = SCOPE_NAME) -> ExportLogsServiceRequest

Build an OTLP ExportLogsServiceRequest, grouping records by identical resource.

endpoint_for

endpoint_for(config: SignozConfig, protocol: OtlpProtocol | str) -> str

Endpoint for protocol: the configured one when the protocols match, otherwise the configured endpoint with the standard port swapped (4318 ↔ 4317).

error_for_code

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

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.

escape_like_pattern

escape_like_pattern(value: str) -> str

Escape a value for CONTAINS/LIKE so it matches literally (\, %, _).

String quoting (:func:quote_filter_string) is applied afterwards.

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).

filter_literal

filter_literal(value: FilterValue) -> str

Render a literal: numbers bare, booleans true/false, strings quoted.

format_timestamp

format_timestamp(value: datetime) -> str

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

get_logger

get_logger() -> logging.Logger

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

grpc_error

grpc_error(code_name: str, detail: str, operation: str, secrets: list[str]) -> ServiceError

Map a gRPC status code name ("UNAVAILABLE"…) to the SPEC error classes.

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 | str, *, signoz: SignozConfig | None = None, propagator_factories: Mapping[str, PropagatorFactory] | None = None, span_processors: Sequence[SpanProcessor] = (), id_generator: IdGenerator | None = None, **overrides: Any) -> TracingHandle

Set up OpenTelemetry tracing that exports to the SigNoz collector (SPEC §5).

config is a :class:TracingConfig or the service name (**overrides are then TracingConfig fields). Endpoint, protocol default and ingestion key come from signoz (default :meth:SignozConfig.from_env); explicit TracingConfig values win. 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.

log_row_to_record

log_row_to_record(row: Any) -> SignozLogRecord

Convert a raw log row ({timestamp, data} from query_range or live tail).

Severity comes from severity_number (fallback: severity_text); attributes merge attributes_string|number|bool; resource is resources_string; empty trace/span ids are absent. A structured body is returned as a JSON string.

mark_span_error

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

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

micros_to_datetime

micros_to_datetime(micros: int) -> datetime

Exact UTC datetime for microseconds since the epoch.

nanos_to_ms

nanos_to_ms(nanos: int) -> int

Epoch milliseconds (floor) of epoch nanoseconds.

new_idempotency_key

new_idempotency_key() -> str

A random key for the Idempotency-Key header.

normalize_headers

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

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

normalize_span_id

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

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

normalize_trace_id

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

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

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

otlp_headers

otlp_headers(config: SignozConfig, extra: Mapping[str, str] | None = None) -> dict[str, str]

Headers for OTLP exports: config headers, extra and the Cloud ingestion key.

otlp_http_url

otlp_http_url(endpoint: str, signal: str) -> str

Append /v1/<signal> to an OTLP/HTTP base endpoint unless it already ends with it.

parse_bool

parse_bool(text: str) -> bool

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

parse_duration

parse_duration(text: str) -> float

Parse a duration into seconds.

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

parse_retry_after

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

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

parse_timestamp

parse_timestamp(value: str) -> datetime

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.

quote_filter_string

quote_filter_string(value: str) -> str

Quote a string literal: '…' with \ → \\ and ' → \'.

record_exception

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

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

redact_fields

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

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

redact_headers

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

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

redact_text

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

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

redact_url

redact_url(url: str) -> str

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

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

resolve_window

resolve_window(start: datetime | None, end: datetime | None, now: datetime | None = None) -> tuple[int, int]

(start_ms, end_ms); defaults: end = now, start = one hour before end.

Raises :class:ValidationError when start is not before end.

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.

rfc3339_to_nanos

rfc3339_to_nanos(text: str) -> int

Parse an RFC 3339 timestamp with up to nanosecond precision into epoch nanoseconds.

Raises :class:ValidationError when invalid.

set_error

set_error(error: BaseException | str) -> None

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

signoz_tracing_config

signoz_tracing_config(config: TracingConfig | str, signoz: SignozConfig | None = None, **overrides: Any) -> TracingConfig

Merge SigNoz defaults under a :class:TracingConfig.

config may be a TracingConfig or just the service name. Without an explicit endpoint, the protocol is signoz.otlp_protocol unless the tracing config picks grpc (http/protobuf is the TracingConfig default and cannot be told apart from "unset", so it follows the SigNoz config — same rule as Rust and Java). The endpoint defaults to the configured collector endpoint for the protocol (4318 ↔ 4317 swapped when the protocols differ), headers get the signoz-ingestion-key (explicit headers win) and TLS defaults to signoz.tls. signoz defaults to :meth:SignozConfig.from_env.

sort_spans

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

Spans sorted by start time, then span id.

span_from_readable

span_from_readable(span: ReadableSpan) -> Span

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

span_kind

span_kind(kind: SpanKindLike) -> SpanKind

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

span_row_to_span

span_row_to_span(row: Any) -> Span | None

Convert a raw span row (requestType: raw, signal: traces); None without ids.

The parent reference SigNoz mirrors into links is dropped; SigNoz does not store link attributes, so they are always {}.

structlog_processor

structlog_processor(client: LogSink) -> StructlogProcessor

Return a structlog processor that sends every event to client.

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

to_attr_value

to_attr_value(value: Any) -> AttrValue

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

to_epoch_ms

to_epoch_ms(value: datetime) -> int

Epoch milliseconds of a datetime (naive values are UTC).

to_seconds

to_seconds(value: float | timedelta) -> float

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

trace_fields

trace_fields() -> dict[str, str]

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

traced

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

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

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

truncate

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

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

user_agent

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

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

wait_for_log

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

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

wait_for_trace

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

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

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

waterfall_span_to_span

waterfall_span_to_span(value: Any) -> Span | None

Convert one waterfall span; None without ids.

time_unix is in milliseconds, so start_micros has millisecond precision. Links come from references with refType: FOLLOWS_FROM.

waterfall_to_trace

waterfall_to_trace(trace_id: str, value: Any) -> SignozTrace

Convert the data of /api/v4/traces/{id}/waterfall.

with_span

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

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

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