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 Grafana Loki.

from grow_grafana_loki import LokiClient, LokiConfig client = LokiClient.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).

Direction module-attribute

Direction = Literal['backward', 'forward']

Sort order of log query results (backward = newest first, Loki's default).

LokiTime module-attribute

LokiTime: TypeAlias = '_dt.datetime | int | str'

A point in time accepted by the Loki API: an aware datetime (naive = UTC), an int of Unix nanoseconds (lossless) or a string (decimal Unix nanoseconds or RFC 3339).

MatchOperator module-attribute

MatchOperator = Literal['=', '!=', '=~', '!~']

Selector / label-filter operators for string values.

NumericOperator module-attribute

NumericOperator = Literal['==', '!=', '>', '>=', '<', '<=']

Numeric label-filter operators.

PushFormat module-attribute

PushFormat = Literal['json', 'protobuf']

Wire format of push: json (default) or protobuf (Snappy-compressed).

AsyncBaseLogQueryClient

Async :class:BaseLogQueryClient.

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

AsyncLokiClient

Bases: _ClientBase

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

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

aclose async

aclose() -> None

Flush and close log clients, stop tails, close connections (idempotent).

build_info async

build_info() -> BuildInfo

See :meth:LokiClient.build_info.

format_query async

format_query(logql: str) -> str

See :meth:LokiClient.format_query.

from_env classmethod

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

Build a client from the GROW_GRAFANA_LOKI_* and LOKI_* environment variables.

health async

health() -> HealthStatus

See :meth:LokiClient.health.

index_stats async

index_stats(query: str, *, start: LokiTime | None = None, end: LokiTime | None = None) -> IndexStats

See :meth:LokiClient.index_stats.

label_values async

label_values(name: str, *, start: LokiTime | None = None, end: LokiTime | None = None, since_s: Duration | None = None, query: str | None = None) -> list[str]

See :meth:LokiClient.label_values.

labels async

labels(*, start: LokiTime | None = None, end: LokiTime | None = None, since_s: Duration | None = None, query: str | None = None) -> list[str]

See :meth:LokiClient.labels.

log_client

log_client(*, options: BatchOptions | None = None, resource: Mapping[str, Any] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True, format: PushFormat = 'json') -> AsyncBatchingLogClient

See :meth:LokiClient.log_client (async log client; flush/close awaited).

log_query

log_query() -> AsyncLokiLogQueryClient

See :meth:LokiClient.log_query.

otlp_log_client

otlp_log_client(*, options: BatchOptions | None = None, resource: Mapping[str, Any] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True) -> AsyncBatchingLogClient

See :meth:LokiClient.otlp_log_client.

ping async

ping() -> float

See :meth:LokiClient.ping.

push async

push(streams: Sequence[LokiStream], *, format: PushFormat = 'json', gzip: bool = False, timeout_s: float | None = None) -> None

See :meth:LokiClient.push.

push_otlp async

push_otlp(records: Sequence[LogRecord], *, gzip: bool = False, timeout_s: float | None = None) -> None

See :meth:LokiClient.push_otlp.

query async

query(logql: str, *, time: LokiTime | None = None, limit: int | None = None, direction: Direction | None = None) -> QueryResult

See :meth:LokiClient.query.

query_range async

query_range(logql: str, *, start: LokiTime | None = None, end: LokiTime | None = None, since_s: Duration | None = None, step_s: Duration | None = None, interval_s: Duration | None = None, limit: int | None = None, direction: Direction | None = None) -> QueryResult

See :meth:LokiClient.query_range.

ready async

ready() -> bool

See :meth:LokiClient.ready.

request async

request(req: Request) -> Response

Send a raw request through the client's transport.

series async

series(matchers: Sequence[str] | str, *, start: LokiTime | None = None, end: LokiTime | None = None, since_s: Duration | None = None) -> list[dict[str, str]]

See :meth:LokiClient.series.

server_version async

server_version() -> str

See :meth:LokiClient.server_version.

tail async

tail(logql: str, on_entries: Callable[[TailFrame], None], *, start: LokiTime | None = None, limit: int | None = None, delay_for_s: float | timedelta | None = None, on_error: Callable[[Exception], None] | None = None) -> AsyncTailSession

See :meth:LokiClient.tail; frames are delivered from a task on the current loop.

volume async

volume(query: str, *, start: LokiTime | None = None, end: LokiTime | None = None, limit: int | None = None, target_labels: Sequence[str] | None = None, aggregate_by: Literal['series', 'labels'] | None = None) -> QueryResult

See :meth:LokiClient.volume.

volume_range async

volume_range(query: str, *, start: LokiTime | None = None, end: LokiTime | None = None, step_s: Duration | None = None, limit: int | None = None, target_labels: Sequence[str] | None = None, aggregate_by: Literal['series', 'labels'] | None = None) -> QueryResult

See :meth:LokiClient.volume_range.

with_tenant

with_tenant(tenant_id: str) -> AsyncLokiClient

See :meth:LokiClient.with_tenant.

AsyncLokiLogExporter

Async :class:LokiLogExporter.

shutdown async

shutdown() -> None

No-op (the client owns the connections).

AsyncLokiLogQueryClient

Bases: AsyncBaseLogQueryClient

Async :class:LokiLogQueryClient (from :meth:AsyncLokiClient.log_query).

list_labels async

list_labels() -> list[str]

Label names of the last hour.

list_streams async

list_streams() -> list[str]

Label sets of the streams of the last hour, as {a="b", c="d"} strings.

tail async

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

Stream new records (WebSocket; interval_s is unused).

AsyncLokiOtlpExporter

Async :class:LokiOtlpExporter.

shutdown async

shutdown() -> None

No-op (the client owns the connections).

AsyncPollingTail

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

AsyncTailSession

A running live tail (async). Implements the logging AsyncTailHandle protocol.

Frames are delivered from a task on the event loop that opened the tail.

done property

done: bool

True once the tail has ended.

dropped_count property

dropped_count: int

Number of entries Loki reported as dropped (slow tailer).

error property

error: ServiceError | None

Why the tail ended (see :attr:TailSession.error).

stop async

stop() -> None

Close the WebSocket (code 1000) and wait for the reader task (idempotent).

wait async

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

Wait until the tail ends (or timeout_s); returns :attr:done.

AuthenticationError

Bases: LokiError

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

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.

BuildInfo dataclass

Loki build information (/loki/api/v1/status/buildinfo).

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: LokiError, 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.

CardinalityGuard

Keeps Loki's index small: only allowlisted keys become labels, the rest is metadata.

allowed property

allowed: list[str]

The allowlist, sorted.

apply

apply(stream: LokiStream) -> LokiStream

Copy of stream whose labels outside the allowlist are moved to every entry's structured metadata (an entry's own metadata wins).

is_allowed

is_allowed(name: str) -> bool

Whether name may be an index label.

split

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

Divide attributes into index labels (allowlisted, scalar, non-empty) and metadata.

Keys are normalized with :func:normalize_label_name; non-string values are rendered with :func:attr_to_string.

ConfigError

Bases: LokiError

Invalid or missing configuration.

ConflictError

Bases: LokiError

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

DroppedEntry dataclass

An entry Loki dropped because the tailer fell behind.

EnvReader

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

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

duration

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

Duration in seconds.

lookup

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

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

ErrorCode

Bases: str, Enum

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

ErrorInfo dataclass

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

ExportResult dataclass

Outcome of one :meth:LogExporter.export call.

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

HealthStatus dataclass

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

Hooks dataclass

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

HttpTransport

Synchronous transport (one per client).

Service options (all optional):

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

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

close

close() -> None

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

request

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

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

IndexStats dataclass

Index statistics (TSDB index only: zero until the ingester flushed its chunks; bytes are tracked per chunk in KB, so small test chunks report 0).

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.

LogQL

Immutable LogQL builder; every method returns a new builder.

LogQL.selector({"app": "x", "env": "prod"}).line_matches("(?i)timeout").build() '{app="x", env="prod"} |~ "(?i)timeout"'

build

build() -> str

Render the query.

Raises :class:ValidationError when the selector is empty or every matcher also matches the empty string (Loki rejects such selectors).

json

json() -> LogQL

Parser stage | json.

label

label(name: str, op: MatchOperator, value: str) -> LogQL

Add a stream-selector matcher (=, !=, =~, !~).

line_contains

line_contains(text: str) -> LogQL

Line filter |= "text" (case-sensitive substring).

line_format

line_format(template: str) -> LogQL

Formatting stage | line_format "<template>".

line_matches

line_matches(regex: str) -> LogQL

Line filter |~ "regex" (RE2; prefix (?i) for case-insensitive).

line_not_contains

line_not_contains(text: str) -> LogQL

Line filter != "text".

line_not_matches

line_not_matches(regex: str) -> LogQL

Line filter !~ "regex".

logfmt

logfmt() -> LogQL

Parser stage | logfmt.

pattern

pattern(pattern: str) -> LogQL

Parser stage | pattern "<pattern>".

pipe

pipe(stage: str) -> LogQL

Append a raw pipeline stage (| <stage>, e.g. drop level); not escaped.

quote staticmethod

quote(value: str) -> str

Quote a string literal (see :func:quote_logql).

regexp

regexp(pattern: str) -> LogQL

Parser stage | regexp "<re>" with named capture groups.

selector classmethod

selector(labels: Mapping[str, str] | None = None) -> LogQL

Start a query from equality matchers ({app="x", env="prod"}).

unpack

unpack() -> LogQL

Parser stage | unpack (lines packed by Promtail's pack stage).

where

where(field: str, op: MatchOperator | NumericOperator, value: str | float) -> LogQL

Label filter on an extracted label or structured-metadata key.

Numbers use the numeric operators (==, !=, >, >=, <, <=); strings use =, !=, =~, !~.

LogQueryClient

Bases: Protocol

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

LogRecord dataclass

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

from_json classmethod

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

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

json_size

json_size() -> int

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

to_json

to_json() -> dict[str, Any]

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

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

to_json_str

to_json_str() -> str

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

LogSearchResult dataclass

One page of search results.

LogSink

Bases: Protocol

Anything that accepts records: every log client.

Logger

Small structured logger writing to a :class:LogSink.

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

child

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

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

LoggerLike

Bases: Protocol

Structured logger interface accepted in configuration (SPEC Logger).

LokiClient

Bases: _ClientBase

Synchronous Grafana Loki 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. Time arguments accept an aware datetime, int Unix nanoseconds or a string (RFC 3339 or decimal nanoseconds); durations accept float seconds, timedelta or Loki text ("5m").

build_info

build_info(*, cancel: CancelToken | None = None) -> BuildInfo

Server build information; :class:UnsupportedError when the endpoint is missing.

close

close() -> None

Flush and close the log clients created by this client, stop its tails and (for a client not made by :meth:with_tenant) close the connections. Idempotent.

format_query

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

Let Loki parse and pretty-print logql; :class:ValidationError if it does not parse.

from_env classmethod

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

Build a client from the GROW_GRAFANA_LOKI_* and LOKI_* environment variables.

health

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

Readiness (GET /ready); never raises for an unhealthy or unreachable service.

healthy is true for HTTP 200; otherwise status is Loki's text (for example Ingester not ready: waiting for 15s after being ready) or unreachable. Configured credentials are sent because gateways may protect /ready. Raises only :class:CancelledError and :class:ConfigError.

index_stats

index_stats(query: str, *, start: LokiTime | None = None, end: LokiTime | None = None, cancel: CancelToken | None = None) -> IndexStats

Index statistics for a selector (GET /loki/api/v1/index/stats).

Values come from the TSDB index and stay zero until the ingester flushed the chunks.

label_values

label_values(name: str, *, start: LokiTime | None = None, end: LokiTime | None = None, since_s: Duration | None = None, query: str | None = None, cancel: CancelToken | None = None) -> list[str]

Values of label name (GET /loki/api/v1/label/{name}/values).

Loki answers unknown and invalid names with an empty list, so the name is validated client-side (:class:ValidationError).

labels

labels(*, start: LokiTime | None = None, end: LokiTime | None = None, since_s: Duration | None = None, query: str | None = None, cancel: CancelToken | None = None) -> list[str]

Label names (GET /loki/api/v1/labels); structured metadata keys are not labels.

log_client

log_client(*, options: BatchOptions | None = None, resource: Mapping[str, Any] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True, format: PushFormat = 'json') -> BatchingLogClient

A batching LogClient pushing to Loki through :class:LokiLogExporter.

resource (service.name, deployment.environment …) is added to every record; :meth:close flushes and closes the log client.

log_query

log_query() -> LokiLogQueryClient

The LogQueryClient of this client (search, tail, list_streams, list_labels, wait_for_log).

otlp_log_client

otlp_log_client(*, options: BatchOptions | None = None, resource: Mapping[str, Any] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True) -> BatchingLogClient

A batching LogClient exporting through Loki's OTLP endpoint (:class:LokiOtlpExporter).

ping

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

Authenticated round trip (GET /loki/api/v1/labels?since=5m); latency in ms.

:class:AuthenticationError on bad gateway credentials or a missing tenant on a multi-tenant Loki.

push

push(streams: Sequence[LokiStream], *, format: PushFormat = 'json', gzip: bool = False, timeout_s: float | None = None, cancel: CancelToken | None = None) -> None

Send streams to Loki (POST /loki/api/v1/push).

Labels are validated client-side and the cardinality guard moves labels outside the allowlist to structured metadata (unless config.disable_label_guard). format is "json" (default; gzip=True compresses it) or "protobuf" (a Snappy compressed PushRequest). The whole request succeeds or fails; Loki rejects entries older than its reject_old_samples_max_age or too far in the future with :class:ValidationError. Retrying is safe (Loki drops exact duplicates), so the transport replays the identical payload on 429/5xx. Empty streams sends nothing.

push_otlp

push_otlp(records: Sequence[LogRecord], *, gzip: bool = False, timeout_s: float | None = None, cancel: CancelToken | None = None) -> None

Send log records as OTLP/JSON to Loki's native OTLP endpoint (/otlp/v1/logs).

Loki promotes service.name, deployment.environment and its other default resource attributes to labels and stores everything else as structured metadata.

query

query(logql: str, *, time: LokiTime | None = None, limit: int | None = None, direction: Direction | None = None, cancel: CancelToken | None = None) -> QueryResult

Instant metric query (GET /loki/api/v1/query).

Loki answers log queries only as range queries, so a log selector ({...}) is rejected with :class:ValidationError before any request: use :meth:query_range or :meth:log_query.

query_range

query_range(logql: str, *, start: LokiTime | None = None, end: LokiTime | None = None, since_s: Duration | None = None, step_s: Duration | None = None, interval_s: Duration | None = None, limit: int | None = None, direction: Direction | None = None, cancel: CancelToken | None = None) -> QueryResult

Range query (GET /loki/api/v1/query_range).

Log queries return streams (each stream ordered by direction; streams are not ordered globally), metric queries return matrix. start is inclusive, end exclusive; without them Loki uses the last hour. Labels are categorized: stream labels are index labels, structured metadata and parsed labels come per entry.

ready

ready(*, cancel: CancelToken | None = None) -> bool

True when GET /ready answers 200, False for 503 (starting); errors otherwise.

request

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

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

Auth and tenant headers are not added automatically; use config.auth_headers().

series

series(matchers: Sequence[str] | str, *, start: LokiTime | None = None, end: LokiTime | None = None, since_s: Duration | None = None, cancel: CancelToken | None = None) -> list[dict[str, str]]

Label sets of the streams matching any selector (POST /loki/api/v1/series).

At least one matcher is required (Loki would otherwise return every series).

server_version

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

The Loki version (build_info().version).

tail

tail(logql: str, on_entries: Callable[[TailFrame], None], *, start: LokiTime | None = None, limit: int | None = None, delay_for_s: float | timedelta | None = None, on_error: Callable[[Exception], None] | None = None) -> TailSession

Stream new entries of a log query over a WebSocket (GET /loki/api/v1/tail).

on_entries is called from one thread for every frame. start replays entries from that time first; without it the tail is live only. The handshake carries the auth, tenant and categorize-labels headers; handshake failures raise (401 → :class:AuthenticationError, 400 → :class:ValidationError). Metric queries and delay_for_s above 5 s are rejected client-side. on_error receives errors of the running tail (and exceptions raised by on_entries). Stop it with :meth:TailSession.stop; :meth:close stops it too.

volume

volume(query: str, *, start: LokiTime | None = None, end: LokiTime | None = None, limit: int | None = None, target_labels: Sequence[str] | None = None, aggregate_by: Literal['series', 'labels'] | None = None, cancel: CancelToken | None = None) -> QueryResult

Ingested bytes per series or label (GET /loki/api/v1/index/volume), a vector.

Needs limits_config.volume_enabled on the server; otherwise Loki returns an empty vector ("no data", not an error).

volume_range

volume_range(query: str, *, start: LokiTime | None = None, end: LokiTime | None = None, step_s: Duration | None = None, limit: int | None = None, target_labels: Sequence[str] | None = None, aggregate_by: Literal['series', 'labels'] | None = None, cancel: CancelToken | None = None) -> QueryResult

:meth:volume over time (GET /loki/api/v1/index/volume_range), a matrix.

with_tenant

with_tenant(tenant_id: str) -> LokiClient

A client that sends X-Scope-OrgID: tenant_id on every request and on the tail handshake. It shares the connection pool and credentials; this client is unchanged.

Raises :class:ValidationError for an invalid tenant id. Closing the derived client stops only its own log clients and tails; the connections close with this client.

LokiConfig dataclass

Bases: BaseConfig

Immutable settings for :class:~grow_grafana_loki.LokiClient.

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.

Loki itself has no authentication: tenant_id is sent as X-Scope-OrgID (needed when Loki runs with auth_enabled: true), and Basic (username/password) or Bearer (bearer_token) credentials are for gateways and hosted Loki (Grafana Cloud: Basic user = instance id, password = access token). The client never interprets them. password and bearer_token accept str and are stored as :class:Secret; repr() never shows them.

Environment (from_env; explicit value > GROW_GRAFANA_LOKI_* > vendor > default):

=============== ======================================================================== url GROW_GRAFANA_LOKI_URL, LOKI_URL tenant_id GROW_GRAFANA_LOKI_TENANT_ID, LOKI_TENANT_ID username GROW_GRAFANA_LOKI_USERNAME, LOKI_USERNAME, LOKI_BASIC_AUTH_USER password GROW_GRAFANA_LOKI_PASSWORD, LOKI_PASSWORD, LOKI_BASIC_AUTH_PASSWORD bearer_token GROW_GRAFANA_LOKI_BEARER_TOKEN, LOKI_BEARER_TOKEN =============== ========================================================================

plus the common CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY and PROXY (all with the GROW_GRAFANA_LOKI_ prefix).

Attributes:

Name Type Description
tenant_id str | None

sent as X-Scope-OrgID on every request and on the tail handshake (None sends no header). See :func:tenant_problem for the rules.

username str | None

HTTP Basic user (together with password).

password Secret | None

HTTP Basic password.

bearer_token Secret | None

sends Authorization: Bearer <token> (not together with Basic).

multi_tenant_queries bool

allow tenant ids joined with | (the server must enable multi_tenant_queries_enabled).

allowed_labels Sequence[str] | None

cardinality guard allowlist used by push and the log exporter; None means :data:DEFAULT_ALLOWED_LABELS.

disable_label_guard bool

send every stream label of push as an index label (the LogRecord exporter always applies the guard).

effective_allowed_labels property

effective_allowed_labels: tuple[str, ...]

The allowlist the cardinality guard uses (allowed_labels or the default).

auth_headers

auth_headers() -> dict[str, str]

Authorization and X-Scope-OrgID headers for every request (may be empty).

known_secrets

known_secrets() -> list[str]

Credential values to redact from error text (password, token, Basic token).

validate

validate() -> _C

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

Username and password go together; Basic and Bearer are mutually exclusive; the tenant id follows :func:tenant_problem; allowlisted label names must be valid label names.

LokiEntry dataclass

One log line pushed to Loki.

Attributes:

Name Type Description
line str

the log line.

timestamp datetime | int | str | None

datetime or int Unix nanoseconds (also a nanosecond / RFC 3339 string); None means "now" at push time.

structured_metadata Mapping[str, str]

per-entry metadata (string → string), stored next to the line but not indexed.

timestamp_ns

timestamp_ns(default: int | None = None) -> int

The timestamp in Unix nanoseconds (default or now when unset).

LokiLogExporter

:class:~grow_grafana_loki.LogExporter writing to POST /loki/api/v1/push.

Records are grouped into streams by the cardinality guard (:func:records_to_streams). Loki accepts or rejects a whole push, so a result is all accepted or all rejected.

shutdown

shutdown() -> None

No-op (the client owns the connections).

LokiLogQueryClient

Bases: BaseLogQueryClient

:class:~grow_grafana_loki.LogQueryClient on Loki (get it from :meth:LokiClient.log_query).

search runs query_range (categorized labels), merge-sorts all streams and pages with an opaque cursor; a query that is not LogQL is treated as free text ({service_name=~".+"} |= "<text>"). tail uses the WebSocket tail (live only).

list_labels

list_labels() -> list[str]

Label names of the last hour.

list_streams

list_streams() -> list[str]

Label sets of the streams of the last hour, as {a="b", c="d"} strings.

tail

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

Stream new records (WebSocket; interval_s is unused, Loki pushes frames).

LokiOtlpExporter

:class:~grow_grafana_loki.LogExporter writing OTLP/JSON to POST /otlp/v1/logs.

Loki then decides which resource attributes become labels (its OTLP defaults) and stores the rest as structured metadata.

shutdown

shutdown() -> None

No-op (the client owns the connections).

LokiStream dataclass

A stream: one label set and its entries (push input).

Keep labels few and low-cardinality; the cardinality guard moves labels outside the allowlist to structured metadata.

NotFoundError

Bases: LokiError

Missing record (HTTP 404).

PermissionDeniedError

Bases: LokiError

Authenticated but not allowed (HTTP 403).

Point dataclass

One metric sample value (timestamp from Loki's float seconds).

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.

QueryResult dataclass

Decoded data of a query response.

Exactly one of streams (log queries), vector (instant metric queries, volume), matrix (range metric queries, volume range) or scalar is filled, per result_type. stats is Loki's raw statistics object (may be empty).

RateLimitError

Bases: LokiError

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

Sample dataclass

One series of an instant vector.

SampleSeries dataclass

One series of a range matrix.

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.

StreamEntry dataclass

One log line returned by Loki.

Attributes:

Name Type Description
timestamp_ns int

Unix nanoseconds (lossless).

line str

the log line.

structured_metadata Mapping[str, str]

metadata of the entry (categorized responses, the SDK default).

parsed Mapping[str, str]

labels extracted by parsers such as | json (categorized responses).

timestamp property

timestamp: datetime

The timestamp as an aware UTC datetime (microsecond precision).

StreamResult dataclass

One stream of a log query result or tail frame.

labels are index labels only (the SDK asks Loki to categorize labels); structured metadata and parsed labels come per entry.

TailFrame dataclass

One message of a live tail.

TailSession

A running live tail (sync). Implements the logging TailHandle protocol.

Frames are delivered from one daemon thread. :meth:stop is idempotent.

done property

done: bool

True once the tail has ended.

dropped_count property

dropped_count: int

Number of entries Loki reported as dropped (slow tailer).

error property

error: ServiceError | None

Why the tail ended: None after :meth:stop or a normal close, VALIDATION when Loki closed it for a bad query, UNAVAILABLE on connection errors.

stop

stop() -> None

Close the WebSocket (code 1000) and wait for the reader thread (idempotent).

wait

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

Block until the tail ends (or timeout_s); returns :attr:done.

TimeoutError

Bases: LokiError

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.

UnavailableError

Bases: LokiError

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

UnsupportedError

Bases: LokiError

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

ValidationError

Bases: LokiError

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

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

attr_to_string

attr_to_string(value: Any) -> str

Render an attribute value as a metadata string (objects and lists as JSON).

current_trace_context

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

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

datetime_to_ns

datetime_to_ns(value: datetime) -> int

Unix nanoseconds of value (naive datetimes are taken as UTC).

entry_to_record

entry_to_record(labels: Mapping[str, str], entry: StreamEntry) -> LogRecord

Normalize one Loki entry into a :class:LogRecord.

body = line; attributes = parsed labels + structured metadata (minus the SDK's own keys); resource = stream labels with well-known keys mapped back to OTel names (service_name → service.name); severity from severity_number / severity_text / detected_level / level; trace ids from trace_id / span_id / trace_flags.

error_for_code

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

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.

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

is_valid_label_name

is_valid_label_name(name: str) -> bool

True when name is a valid, non-reserved Loki label name.

label_set_string

label_set_string(labels: Mapping[str, str]) -> str

Prometheus label-set syntax with sorted names and quoted values: {a="b", c="d"}.

new_idempotency_key

new_idempotency_key() -> str

A random key for the Idempotency-Key header.

normalize_label_name

normalize_label_name(key: str) -> str

Turn an attribute key into a label / metadata name the way Loki does for OTLP.

Every character outside [a-zA-Z0-9_] becomes _ (service.name → service_name) and a leading digit gets a _ prefix. An empty key stays empty.

ns_to_datetime

ns_to_datetime(ns: int | str) -> _dt.datetime

Aware UTC datetime of Unix nanoseconds (microsecond precision).

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_logql

quote_logql(value: str) -> str

Quote a LogQL string literal with Go/JSON escaping (", \, newlines, tabs; Unicode stays as is). Verified against Loki 3.7 (format_query and round trips).

records_to_streams

records_to_streams(records: Iterable[LogRecord], guard: CardinalityGuard | None = None) -> list[LokiStream]

Map log records to Loki streams with the cardinality guard.

Resource and attribute keys are normalized (service.name → service_name); keys in the allowlist with scalar, non-empty values become index labels, everything else becomes structured metadata. level (the lower-case severity text) is added as a label when allowed. Severity, trace id, span id and trace flags travel as metadata (severity_text, severity_number, trace_id, span_id, trace_flags) and are never labels. Records with the same final label set share a stream.

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.

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.

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.

tenant_problem

tenant_problem(tenant_id: str, multi_tenant_queries: bool = False) -> str | None

Why tenant_id is not a valid Loki tenant id, or None when it is valid.

Rules (verified against Loki 3.7): not empty, at most 150 bytes, not . or .., characters [A-Za-z0-9!-_.*'()] only. | joins tenants for a multi-tenant query and is accepted only when multi_tenant_queries is set (each part must then be valid).

to_attr_value

to_attr_value(value: Any) -> AttrValue

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

to_logql

to_logql(query: str) -> str

query when it is LogQL (starts with {), else a line filter over every stream: {service_name=~".+"} |= "<text>" (an empty query selects every stream).

to_ns

to_ns(value: LokiTime, field: str = 'time') -> str

Render a :data:LokiTime as the decimal nanosecond string Loki expects.

Raises :class:ValidationError for negative numbers or unparsable text.

to_seconds

to_seconds(value: float | timedelta) -> float

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

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.

validate_label

validate_label(name: str, value: str) -> None

Check one index label; raise :class:ValidationError.

The name must match [a-zA-Z_][a-zA-Z0-9_]* and must not start with __ (reserved); the value must be a non-empty string.

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.