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
¶
Attribute value: scalar, list of values or nested mapping (OTel AnyValue without bytes).
Direction
module-attribute
¶
Sort order of log query results (backward = newest first, Loki's default).
LokiTime
module-attribute
¶
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
¶
Selector / label-filter operators for string values.
NumericOperator
module-attribute
¶
Numeric label-filter operators.
PushFormat
module-attribute
¶
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 ¶
Queue without blocking; False when dropped (block acts as drop_newest here).
add_wait
async
¶
Queue a record, waiting for queue space with drop_policy="block".
flush
async
¶
Export everything queued now; raises TimeoutError when timeout_s passes first.
shutdown
async
¶
Drain (bounded by timeout_s), stop the task, shut the exporter down; idempotent.
AsyncBatchingLogClient ¶
Bases: _ClientBase
:class:AsyncLogClient over an :class:AsyncLogExporter + :class:AsyncBatchProcessor.
AsyncHttpTransport ¶
Asynchronous transport (one per async client); options as for :class:HttpTransport.
Cancelling the calling task raises :class:CancelledError (an asyncio.CancelledError
subclass) so asyncio's cancellation machinery keeps working. Every call after
:meth:aclose raises :class:CancelledError ("client is closed").
AsyncLogClient ¶
Bases: Protocol
Asynchronous log client: send stays synchronous, flush/close are awaited.
AsyncLogExporter ¶
Bases: Protocol
Asynchronous exporter, awaited by :class:AsyncBatchProcessor on the caller's event loop.
AsyncLogQueryClient ¶
Bases: Protocol
Asynchronous query API (same methods, awaited).
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
¶
Flush and close log clients, stop tails, close connections (idempotent).
from_env
classmethod
¶
Build a client from the GROW_GRAFANA_LOKI_* and LOKI_* environment variables.
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).
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.
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.
request
async
¶
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.
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.
AsyncLokiLogExporter ¶
Async :class:LokiLogExporter.
AsyncLokiLogQueryClient ¶
Bases: AsyncBaseLogQueryClient
Async :class:LokiLogQueryClient (from :meth:AsyncLokiClient.log_query).
list_streams
async
¶
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.
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.
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.
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
¶
Build from the camelCase form used by conformance scenarios (flushIntervalMs …).
BatchProcessor ¶
Bases: _BatchCore
Batches records for a synchronous :class:LogExporter on a daemon worker thread.
The worker starts with the first record. It exports when a batch is full, when
flush_interval_s passed since the first queued record, on :meth:flush and on
:meth:shutdown. Processors with a started worker are shut down at interpreter exit.
add ¶
Queue a record; False when it was dropped. Blocks only with drop_policy="block".
flush ¶
Export everything queued now; raises TimeoutError when timeout_s passes first.
shutdown ¶
Drain the queue (bounded by timeout_s), stop the worker and shut the exporter down.
Idempotent. Records still queued when the timeout passes are dropped with reason
shutdown; later :meth:add calls are dropped the same way.
BatchStats
dataclass
¶
Counters of a batch processor (see the module docs for their meaning).
BatchingLogClient ¶
Bases: _ClientBase
:class:LogClient over a synchronous :class:LogExporter and a :class:BatchProcessor.
redaction defaults to RedactionProcessor(); pass None to disable it.
correlate adds the active span's ids to records without a trace id.
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.
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.
apply ¶
Copy of stream whose labels outside the allowlist are moved to every entry's
structured metadata (an entry's own metadata wins).
split ¶
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.
ErrorCode ¶
Bases: str, Enum
Canonical error codes; the value is the wire form used by the conformance suite.
ErrorInfo
dataclass
¶
Passed to Hooks.on_error; error is the (redacted) SDK error.
ExportResult
dataclass
¶
Outcome of one :meth:LogExporter.export call.
retries is a Python extension: the number of transport retries the export needed
(summed into BatchStats.retries).
HealthStatus
dataclass
¶
Result of health(); status is ok/degraded/unhealthy/unreachable or a vendor word.
Hooks
dataclass
¶
Optional callbacks invoked on every attempt. Exceptions raised by hooks are ignored.
HttpTransport ¶
Synchronous transport (one per client).
Service options (all optional):
request_id_headers: vendor request id headers, checked before :data:REQUEST_ID_HEADERS.retry_after_headers: headers read (in order) for the delay a 429/503 response asks for; default("retry-after",), e.g.("retry-after", "x-ratelimit-reset"). See :func:retry_after_from_headers.error_mapper:mapper(error, response)returns a service-specific error for an HTTP error response (orNoneto keep the default). The mapped error is whatHooks.on_error, the retry planner (retry_after) and the caller see; whether a status is retried stays the SPEC rule. Exceptions raised by the mapper are logged and ignored.
Every call after :meth:close raises :class:CancelledError ("client is closed").
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 ¶
Render the query.
Raises :class:ValidationError when the selector is empty or every matcher also
matches the empty string (Loki rejects such selectors).
label ¶
Add a stream-selector matcher (=, !=, =~, !~).
line_matches ¶
Line filter |~ "regex" (RE2; prefix (?i) for case-insensitive).
pipe ¶
Append a raw pipeline stage (| <stage>, e.g. drop level); not escaped.
selector
classmethod
¶
Start a query from equality matchers ({app="x", env="prod"}).
where ¶
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
¶
Parse the normalized wire form; raises ValidationError for malformed input.
to_json ¶
Normalized wire form (spec/schemas/log-record.schema.json, camelCase keys).
severity is the OTel number; timestamps are RFC 3339 UTC with microseconds.
to_json_str ¶
Compact JSON text of :meth:to_json (UTF-8 safe, non-JSON values via str).
LogSearchResult
dataclass
¶
One page of search results.
LogSink ¶
Bases: Protocol
Anything that accepts records: every log client.
Logger ¶
Small structured logger writing to a :class:LogSink.
Records below min_severity are discarded. The sink fills timestamp, resource and trace
correlation (the active OpenTelemetry span) for records without a trace id.
child ¶
Logger with the same sink and level and the extra attributes.
LoggerLike ¶
Bases: Protocol
Structured logger interface accepted in configuration (SPEC Logger).
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 ¶
Server build information; :class:UnsupportedError when the endpoint is missing.
close ¶
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 ¶
Let Loki parse and pretty-print logql; :class:ValidationError if it does not
parse.
from_env
classmethod
¶
Build a client from the GROW_GRAFANA_LOKI_* and LOKI_* environment variables.
health ¶
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 ¶
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 ¶
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 ¶
True when GET /ready answers 200, False for 503 (starting); errors otherwise.
request ¶
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 ¶
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 ¶
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 |
username |
str | None
|
HTTP Basic user (together with |
password |
Secret | None
|
HTTP Basic password. |
bearer_token |
Secret | None
|
sends |
multi_tenant_queries |
bool
|
allow tenant ids joined with |
allowed_labels |
Sequence[str] | None
|
cardinality guard allowlist used by |
disable_label_guard |
bool
|
send every stream label of |
effective_allowed_labels
property
¶
The allowlist the cardinality guard uses (allowed_labels or the default).
auth_headers ¶
Authorization and X-Scope-OrgID headers for every request (may be empty).
known_secrets ¶
Credential values to redact from error text (password, token, Basic token).
validate ¶
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
|
|
structured_metadata |
Mapping[str, str]
|
per-entry metadata (string → string), stored next to the line but not indexed. |
timestamp_ns ¶
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.
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_streams ¶
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.
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.
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.
Request
dataclass
¶
One logical API call (possibly several attempts).
path is joined to the base URL ({name} style values must already be encoded; use
:func:urllib.parse.quote); an absolute http:///https:// URL is used as is (for
pagination links the service returns; the default headers, config.headers included,
are sent there too, so only pass URLs of the same service). json is encoded when not
None; content sends raw bytes. idempotent overrides the method rule; an
idempotency_key sends the Idempotency-Key header and marks the request idempotent.
raise_for_status=False returns error responses instead of raising (retries still
apply). Statuses in allow_status are expected answers (a 404 that carries data, a
health endpoint's 503): the response is returned at once, like a success, without retries
or on_error.
RequestInfo
dataclass
¶
Passed to Hooks.on_request; url and headers are redacted.
ResourceRegistry ¶
Holds :class:Stoppable objects; :meth:stop_all stops each once, ignoring errors.
register ¶
Track item; when the registry is already closed the item is stopped now.
Response
dataclass
¶
A completed HTTP response (body fully read).
ResponseInfo
dataclass
¶
Passed to Hooks.on_response; headers are the redacted response headers (rate
limit headers and the like stay readable).
RetryPolicy
dataclass
¶
Retry settings. Durations are seconds (datetime.timedelta is accepted).
Backoff for retry n (0-based) is full jitter:
random(0, min(max_backoff, initial_backoff * multiplier ** n)).
random returns a float in [0, 1); inject it in tests for deterministic sleeps.
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')
Severity ¶
Bases: IntEnum
Log severity; the values are the OpenTelemetry severity numbers.
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 |
timestamp
property
¶
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.
dropped_count
property
¶
Number of entries Loki reported as dropped (slow tailer).
error
property
¶
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.
wait ¶
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 ¶
Render an attribute value as a metadata string (objects and lists as JSON).
current_trace_context ¶
(trace_id, span_id, trace_flags) of the active OpenTelemetry span, if any.
datetime_to_ns ¶
Unix nanoseconds of value (naive datetimes are taken as UTC).
entry_to_record ¶
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 ¶
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 ¶
RFC 3339 UTC form with microseconds and Z; naive datetimes are taken as UTC.
get_logger ¶
The package logger (LOGGER_NAME), silent by default (NullHandler).
is_valid_label_name ¶
True when name is a valid, non-reserved Loki label name.
label_set_string ¶
Prometheus label-set syntax with sorted names and quoted values: {a="b", c="d"}.
normalize_label_name ¶
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 ¶
Aware UTC datetime of Unix nanoseconds (microsecond precision).
parse_bool ¶
Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.
parse_duration ¶
Parse a duration into seconds.
Accepts integer milliseconds ("1500" → 1.5) or Go-style units ("500ms", "10s",
"2m", "1h", "1m30s"). Raises :class:ValueError for anything else.
parse_retry_after ¶
Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.
parse_timestamp ¶
Parse RFC 3339 (any fraction precision, Z/offset; none = UTC) to aware UTC.
poll_until ¶
poll_until(fn: Callable[[], T | None], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic) -> T
Call fn every interval_s until it returns a ready value; return that value.
A value is ready when it is not None and predicate(value) is true (without a
predicate: not an empty container). Retryable SDK errors raised by fn are remembered
and polling continues; other errors propagate. Raises :class:TimeoutError after timeout_s.
quote_logql ¶
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 ¶
Recursively redact values whose key looks sensitive in nested mappings and lists.
redact_headers ¶
Copy of headers with sensitive values replaced by [REDACTED].
redact_text ¶
Replace every known secret value (length >= 4) in text with [REDACTED].
redact_url ¶
Redact user info and every query value (all values, not only sensitive ones).
Query names are kept so the URL stays useful in logs.
retry_after_from_headers ¶
retry_after_from_headers(headers: Headers | Mapping[str, str], names: Sequence[str] = RETRY_AFTER_HEADERS, *, now: Callable[[], float] = time.time) -> float | None
Server requested delay in seconds from the first of names that parses.
Retry-After is delta seconds or an HTTP-date. Other headers (X-RateLimit-Reset,
RateLimit-Reset …) may be delta seconds or a Unix timestamp in seconds or milliseconds;
timestamps are turned into the remaining delay.
structlog_processor ¶
Return a structlog processor that sends every event to client.
The event dict passes through unchanged, so put this processor before the renderer.
event becomes the body, level (or the method name) the severity, timestamp
(TimeStamper output, epoch float or datetime) the timestamp; exc_info and a rendered
exception become exception.* attributes; every other key is an attribute.
tenant_problem ¶
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 ¶
Convert any Python value to an attribute value (unknown types become str(value)).
to_logql ¶
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 ¶
Render a :data:LokiTime as the decimal nanosecond string Loki expects.
Raises :class:ValidationError for negative numbers or unparsable text.
to_seconds ¶
Normalise a duration given as float seconds or :class:datetime.timedelta.
truncate ¶
Truncate text to limit characters (adds an ellipsis when cut).
user_agent ¶
grow-codes-<key>/<version> (python) plus <suffix> when given.
validate_label ¶
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.