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 Graylog Open.

from grow_graylog import GraylogClient, GraylogConfig client = GraylogClient.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).

GelfCompression module-attribute

GelfCompression = Literal['gzip', 'zlib', 'none']

Payload compression of :class:GelfUdpTransport.

GelfFieldValue module-attribute

GelfFieldValue = str | int | float

A GELF additional field value as written on the wire.

GelfProtocol module-attribute

GelfProtocol = Literal['udp', 'tcp', 'http']

GELF transport protocol.

LogProtocol module-attribute

LogProtocol = Literal['udp', 'tcp', 'http', 'otlp']

Transport of :meth:GraylogClient.log_client: a GELF protocol or otlp (gRPC).

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

AsyncGraylogClient

Bases: _ClientCore

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

Same methods as :class:GraylogClient, awaited. Cancel a call by cancelling its task: the SDK raises :class:CancelledError, which is also an :class:asyncio.CancelledError. GELF and OTLP exports run in worker threads.

aclose async

aclose() -> None

Flush and close every log client, then release connections (idempotent).

create_input async

create_input(input_type: str, configuration: Mapping[str, Any], *, title: str | None = None, global_: bool = True, node: str | None = None) -> str

See :meth:GraylogClient.create_input.

create_stream async

create_stream(title: str, *, description: str = '', index_set_id: str | None = None, rules: Sequence[StreamRule] = (), matching_type: Literal['AND', 'OR'] = 'AND', remove_matches_from_default_stream: bool = False, start: bool = True) -> str

See :meth:GraylogClient.create_stream.

delete_input async

delete_input(input_id: str) -> None

See :meth:GraylogClient.delete_input.

delete_stream async

delete_stream(stream_id: str) -> None

See :meth:GraylogClient.delete_stream.

ensure_gelf_input async

ensure_gelf_input(protocol: GelfProtocol, port: int, *, title: str | None = None, bind_address: str = '0.0.0.0', configuration: Mapping[str, Any] | None = None, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 0.5) -> EnsuredInput

See :meth:GraylogClient.ensure_gelf_input.

from_env classmethod

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

Build a client from the GROW_GRAYLOG_* and vendor environment variables.

get_input async

get_input(input_id: str) -> GraylogInput

See :meth:GraylogClient.get_input.

get_input_state async

get_input_state(input_id: str) -> InputState

See :meth:GraylogClient.get_input_state.

get_message async

get_message(index: str, message_id: str) -> GraylogMessage

See :meth:GraylogClient.get_message.

get_stream async

get_stream(stream_id: str) -> GraylogStream

See :meth:GraylogClient.get_stream.

health async

health() -> HealthStatus

See :meth:GraylogClient.health.

list_fields async

list_fields() -> list[str]

See :meth:GraylogClient.list_fields.

list_index_sets async

list_index_sets() -> list[IndexSet]

See :meth:GraylogClient.list_index_sets.

list_input_types async

list_input_types() -> dict[str, str]

See :meth:GraylogClient.list_input_types.

list_inputs async

list_inputs() -> list[GraylogInput]

See :meth:GraylogClient.list_inputs.

list_streams async

list_streams(*, page: int = 1, per_page: int = 50, query: str | None = None, sort: str = 'title', order: Literal['asc', 'desc'] = 'asc') -> StreamPage

See :meth:GraylogClient.list_streams.

log_client

log_client(protocol: LogProtocol | None = None, *, host: str | None = None, transport: GelfTransport | None = None, compression: GelfCompression | None = None, chunk_size: int | None = None, bulk: bool | None = None, headers: Mapping[str, str] | None = None, bearer_token: str | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _UNSET, correlate: bool = True) -> AsyncBatchingLogClient

Async batching log client; see :meth:GraylogClient.log_client.

log_query_client

log_query_client(*, streams: Sequence[str] | None = None, default_window_s: float | timedelta = 3600.0) -> AsyncGraylogLogQueryClient

An :class:AsyncGraylogLogQueryClient.

ping async

ping() -> float

See :meth:GraylogClient.ping.

request async

request(req: Request) -> Response

Send a raw request through the client's transport.

resume_stream async

resume_stream(stream_id: str) -> None

See :meth:GraylogClient.resume_stream.

search async

search(query: str, *, range_s: int | None = None, from_: datetime | None = None, to: datetime | None = None, keyword: str | None = None, limit: int = 100, offset: int = 0, fields: Sequence[str] | None = None, sort: SearchSort | Sequence[SearchSort] | None = None, streams: Sequence[str] | None = None) -> SearchResult

See :meth:GraylogClient.search.

search_relative async

search_relative(query: str, seconds: int, *, limit: int = 100, offset: int = 0, fields: Sequence[str] | None = None, sort: SearchSort | Sequence[SearchSort] | None = None, streams: Sequence[str] | None = None) -> SearchResult

See :meth:GraylogClient.search_relative.

server_version async

server_version() -> str

See :meth:GraylogClient.server_version.

system_info async

system_info() -> SystemInfo

See :meth:GraylogClient.system_info.

AsyncGraylogLogQueryClient

Bases: _QueryBase, AsyncBaseLogQueryClient

Async :class:GraylogLogQueryClient on top of :class:AsyncGraylogClient.

list_labels async

list_labels() -> list[str]

Every indexed field name.

list_streams async

list_streams() -> list[str]

Titles of every stream (all pages).

search async

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

Search records; cursor is the offset of the next page.

tail async

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

Poll for new matching records every interval_s (default 2 s) on the loop.

Same behaviour as :meth:GraylogLogQueryClient.tail.

AsyncGraylogTail

Polling tail of :meth:AsyncGraylogLogQueryClient.tail (a task on the running loop).

:meth:stop is idempotent; closing the client stops the tail too.

cancel

cancel() -> None

Stop without waiting (used by client.close()).

poll_once async

poll_once() -> int

Run one poll; returns the number of delivered records.

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.

AuthenticationError

Bases: GraylogError

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

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: GraylogError, 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: GraylogError

Invalid or missing configuration.

ConflictError

Bases: GraylogError

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

EnsuredInput dataclass

Bases: GraylogInput

Result of :meth:GraylogClient.ensure_gelf_input.

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

GelfHttpTransport

Bases: _TransportBase

GELF over HTTP: POST <url> with JSON bodies, bulk and gzip by default.

Bulk bodies are newline-delimited and every message ends with \n (Graylog 7.0 drops the first message of a later request on a kept-alive connection otherwise). Graylog answers 202 even for messages it drops, so messages are validated client side. Retries, timeouts, TLS, proxy and hooks come from the shared HTTP transport.

Parameters:

Name Type Description Default
url str

full endpoint, e.g. http://graylog:12202/gelf.

required
gzip bool

gzip request bodies (Content-Encoding: gzip); default True.

True
bulk bool

all messages of a batch in one request (input option enable_bulk_receiving); when False, one request per message. Default True.

True
headers Mapping[str, str] | None

extra headers, e.g. the input's authorization_header_name/value.

None
config BaseConfig | None

timeouts, retry, TLS, proxy, hooks and logger (e.g. a GraylogConfig); its url and headers are ignored.

None
http_transport BaseTransport | None

test seam (an httpx transport).

None

send

send(messages: Sequence[GelfMessage], *, gzip: bool | None = None, cancel: CancelToken | None = None) -> GelfSendResult

POST the messages (one bulk request, or one request each with bulk=False).

GelfLevel

Bases: IntEnum

Syslog severity levels used by the GELF level field.

GelfLogExporter

:class:LogExporter that converts records with :meth:GelfMessage.from_log_record and sends them through a :class:GelfTransport. Use it with BatchingLogClient (or client.log_client()).

Parameters:

Name Type Description Default
transport GelfTransport

the GELF transport (closed by :meth:shutdown).

required
host str | None

GELF host for records without resource["host.name"].

None

GelfMessage

One GELF 1.1 message.

Build it with the constructor and :meth:set_field, or from a :class:LogRecord with :meth:from_log_record; serialise with :meth:to_json (dict), :meth:to_json_str or :meth:encode (UTF-8 bytes).

Parameters:

Name Type Description Default
host str

source host (stored as source); required, not blank.

required
short_message str

short message (stored as message); required, not blank.

required
full_message str | None

long message (e.g. a stack trace).

None
timestamp datetime | float | None

event time, a datetime or Unix seconds.

None
level GelfLevel | int | None

syslog level 0-7.

None
fields Mapping[str, Any] | None

additional fields; keys are validated like :meth:set_field.

None

Raises:

Type Description
ValidationError

for a blank host or message, a bad level, timestamp or field key.

fields property

fields: dict[str, GelfFieldValue]

Additional fields with their _ keys (a copy).

encode

encode() -> bytes

UTF-8 JSON bytes.

from_log_record classmethod

from_log_record(record: LogRecord, *, host: str | None = None) -> GelfMessage

Convert a log record (decision 3).

host = resource["host.name"] (else the host argument, else the machine host name), short_message = body ("-" when blank), timestamp, level from the severity, resource attributes flattened with dotted keys (except host.name), then the record attributes, then _trace_id, _span_id, _trace_flags. Keys are sanitised with :func:gelf_field_key, values mapped with :func:gelf_field_value.

set_field

set_field(key: str, value: Any) -> GelfMessage

Set an additional field (name or _name); returns self for chaining.

The key is validated (:func:validate_gelf_field_key); the value is mapped by :func:gelf_field_value and a None value removes the field.

to_json

to_json() -> dict[str, Any]

The GELF wire object.

to_json_str

to_json_str() -> str

Compact JSON text.

GelfSendResult dataclass

Outcome of :meth:GelfTransport.send.

GelfTcpTransport

Bases: _TransportBase

GELF over TCP: one persistent connection, each message JSON + one NUL byte, optional TLS.

A failed connect or write closes the connection and retries the whole batch on a new one with backoff (at-least-once: a batch may be delivered twice after a broken connection).

Parameters:

Name Type Description Default
host str

Graylog host.

required
port int

GELF TCP port (default 12201).

DEFAULT_GELF_PORT
tls bool | TlsConfig

True or a :class:TlsConfig to connect with TLS (default plain TCP).

False
server_hostname str | None

SNI / certificate host name (default host unless it is an IP).

None
connect_timeout_s float

connection setup timeout (default 10 s).

10.0
write_timeout_s float

deadline for writing one batch (default 30 s).

30.0
retry RetryPolicy | None

reconnect policy (default RetryPolicy(), 3 retries).

None

secure property

secure: bool

Whether the transport uses TLS.

frame staticmethod

frame(messages: Sequence[GelfMessage]) -> bytes

Encode messages as NUL-terminated JSON frames.

send

send(messages: Sequence[GelfMessage], *, gzip: bool | None = None, cancel: CancelToken | None = None) -> GelfSendResult

Write all messages on the connection (gzip is ignored: GELF TCP is uncompressed).

GelfTransport

Bases: Protocol

Sends GELF messages to a Graylog input.

asend async

asend(messages: Sequence[GelfMessage], *, gzip: bool | None = None) -> GelfSendResult

:meth:send in a worker thread.

close

close() -> None

Release sockets; idempotent. Later sends raise :class:ConfigError.

send

send(messages: Sequence[GelfMessage], *, gzip: bool | None = None, cancel: CancelToken | None = None) -> GelfSendResult

Send the messages.

Network failures raise (:class:UnavailableError, :class:TimeoutError, :class:CancelledError); client-side rejections are counted in the result.

GelfUdpTransport

Bases: _TransportBase

GELF over UDP: fire-and-forget datagrams, compressed, chunked up to 128 chunks.

Parameters:

Name Type Description Default
host str

Graylog host.

required
port int

GELF UDP port (default 12201).

DEFAULT_GELF_PORT
compression GelfCompression

gzip (default), zlib or none.

'gzip'
chunk_size int

bytes per datagram including the 12-byte chunk header (64..65507).

DEFAULT_UDP_CHUNK_SIZE

send

send(messages: Sequence[GelfMessage], *, gzip: bool | None = None, cancel: CancelToken | None = None) -> GelfSendResult

Send each message as one datagram or a chunk sequence (gzip is ignored).

GraylogClient

Bases: _ClientCore

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

Every REST method accepts cancel= (a :class:CancelToken) to abort from another thread.

Parameters:

Name Type Description Default
config GraylogConfig | None

the configuration (default: :meth:GraylogConfig.from_env).

None
http_transport BaseTransport | None

test seam (an httpx transport, e.g. respx or MockTransport).

None

close

close() -> None

Flush and close every log client from :meth:log_client, then release connections.

Idempotent.

create_input

create_input(input_type: str, configuration: Mapping[str, Any], *, title: str | None = None, global_: bool = True, node: str | None = None, cancel: CancelToken | None = None) -> str

Create an input (POST /api/system/inputs); returns its id.

Unknown types raise :class:NotFoundError. Graylog does not reject a busy port here: check :meth:get_input_state (or use :meth:ensure_gelf_input).

create_stream

create_stream(title: str, *, description: str = '', index_set_id: str | None = None, rules: Sequence[StreamRule] = (), matching_type: Literal['AND', 'OR'] = 'AND', remove_matches_from_default_stream: bool = False, start: bool = True, cancel: CancelToken | None = None) -> str

Create a stream (POST /api/streams); returns its id.

Uses the default index set unless index_set_id is given and resumes the stream unless start=False (Graylog creates streams paused).

delete_input

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

Delete an input: DELETE /api/system/inputs/{id}; :class:NotFoundError.

delete_stream

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

Delete a stream: DELETE /api/streams/{id}; :class:NotFoundError when unknown.

ensure_gelf_input

ensure_gelf_input(protocol: GelfProtocol, port: int, *, title: str | None = None, bind_address: str = '0.0.0.0', configuration: Mapping[str, Any] | None = None, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 0.5, cancel: CancelToken | None = None) -> EnsuredInput

Return a running GELF input for protocol and port, creating it when missing.

Inputs are matched by type, port and bind address. Waits until the input is RUNNING; a FAILED input (e.g. port in use) raises :class:ConflictError and an input created by this call is deleted again. :class:TimeoutError after timeout_s.

from_env classmethod

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

Build a client from the GROW_GRAYLOG_* and vendor environment variables.

get_input

get_input(input_id: str, *, cancel: CancelToken | None = None) -> GraylogInput

One input: GET /api/system/inputs/{id}; :class:NotFoundError when unknown.

get_input_state

get_input_state(input_id: str, *, cancel: CancelToken | None = None) -> InputState

Runtime state of an input: GET /api/system/inputstates/{id}.

get_message

get_message(index: str, message_id: str, *, cancel: CancelToken | None = None) -> GraylogMessage

One stored message: GET /api/messages/{index}/{id}; :class:NotFoundError.

get_stream

get_stream(stream_id: str, *, cancel: CancelToken | None = None) -> GraylogStream

One stream: GET /api/streams/{id}; :class:NotFoundError when unknown.

health

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

Unauthenticated liveness: GET /api/system/lbstatus.

ALIVE → healthy ok, 429 THROTTLED → degraded, 503 DEAD → unhealthy, network errors → unreachable. Never raises for an unhealthy or unreachable service (only :class:CancelledError and :class:ConfigError).

list_fields

list_fields(*, cancel: CancelToken | None = None) -> list[str]

Every indexed field name, sorted: GET /api/system/fields.

list_index_sets

list_index_sets(*, cancel: CancelToken | None = None) -> list[IndexSet]

Every index set: GET /api/system/indices/index_sets?skip_stats=true.

list_input_types

list_input_types(*, cancel: CancelToken | None = None) -> dict[str, str]

Installed input types, class name → human name: GET /api/system/inputs/types.

list_inputs

list_inputs(*, cancel: CancelToken | None = None) -> list[GraylogInput]

Every configured input: GET /api/system/inputs.

list_streams

list_streams(*, page: int = 1, per_page: int = 50, query: str | None = None, sort: str = 'title', order: Literal['asc', 'desc'] = 'asc', cancel: CancelToken | None = None) -> StreamPage

One page of streams: GET /api/streams/paginated (page is 1-based).

log_client

log_client(protocol: LogProtocol | None = None, *, host: str | None = None, transport: GelfTransport | None = None, compression: GelfCompression | None = None, chunk_size: int | None = None, bulk: bool | None = None, headers: Mapping[str, str] | None = None, bearer_token: str | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _UNSET, correlate: bool = True) -> BatchingLogClient

A batching log client sending through GELF (udp, tcp, http) or OTLP.

Parameters:

Name Type Description Default
protocol LogProtocol | None

transport (default config.gelf_protocol); otlp uses the OpenTelemetry (gRPC) input at config.otlp_grpc_endpoint().

None
host str | None

GELF host for records without resource["host.name"].

None
transport GelfTransport | None

use this GELF transport instead of building one (closed with the client).

None
compression GelfCompression | None

UDP payload compression (default gzip).

None
chunk_size int | None

UDP chunk size (default 1420).

None
bulk bool | None

HTTP bulk bodies (default True).

None
headers Mapping[str, str] | None

HTTP/OTLP extra headers (e.g. the input authorization header).

None
bearer_token str | None

OTLP bearer token configured on the input.

None
options BatchOptions | None

batching options.

None
resource Mapping[str, AttrValue] | None

resource attributes of every record (service.name …).

None
redaction RedactionProcessor | None

redaction processor (default RedactionProcessor(); None disables).

_UNSET
correlate bool

add the active OpenTelemetry span ids to records.

True

Log clients are flushed and closed by :meth:close.

log_query_client

log_query_client(*, streams: Sequence[str] | None = None, default_window_s: float | timedelta = 3600.0) -> GraylogLogQueryClient

A :class:GraylogLogQueryClient (search, polling tail, streams, fields).

ping

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

Authenticated round trip (GET /api/system); returns the latency in ms.

request

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

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

resume_stream

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

Start (resume) a paused stream: POST /api/streams/{id}/resume.

search

search(query: str, *, range_s: int | None = None, from_: datetime | None = None, to: datetime | None = None, keyword: str | None = None, limit: int = 100, offset: int = 0, fields: Sequence[str] | None = None, sort: SearchSort | Sequence[SearchSort] | None = None, streams: Sequence[str] | None = None, cancel: CancelToken | None = None) -> SearchResult

Search messages with a Lucene query (POST /api/views/search/sync).

Give at most one of range_s (relative seconds; default 300), from_/to (absolute; from_ defaults to to - 300 s, to to now) and keyword (e.g. "last five minutes"). fields limits the returned fields (plus _id), sort defaults to timestamp descending, streams limits the search to stream ids. An empty query matches everything. Query errors (HTTP 200 with errors) raise :class:ValidationError.

search_relative

search_relative(query: str, seconds: int, *, limit: int = 100, offset: int = 0, fields: Sequence[str] | None = None, sort: SearchSort | Sequence[SearchSort] | None = None, streams: Sequence[str] | None = None, cancel: CancelToken | None = None) -> SearchResult

:meth:search over the last seconds seconds (relative range).

server_version

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

Server version reported by GET /api/system, e.g. 7.0.16+58e0f6e.

system_info

system_info(*, cancel: CancelToken | None = None) -> SystemInfo

Node and cluster information: GET /api/system.

GraylogConfig dataclass

Bases: BaseConfig

Immutable settings for :class:~grow_graylog.GraylogClient.

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

Environment (:meth:from_env), precedence: explicit keyword > GROW_GRAYLOG_<NAME> > vendor variable > platform alias > default.

============== ====================== ============================================ Field GROW_GRAYLOG_* Vendor / platform ============== ====================== ============================================ url URL GRAYLOG_URL api_token API_TOKEN GRAYLOG_API_TOKEN username USER GRAYLOG_USER password PASSWORD GRAYLOG_PASSWORD gelf_host GELF_HOST GRAYLOG_GELF_HOST, GRAYLOG_HOST gelf_port GELF_PORT GRAYLOG_GELF_PORT, GRAYLOG_PORT gelf_protocol GELF_PROTOCOL GRAYLOG_GELF_PROTOCOL, GRAYLOG_TRANSPORT gelf_http_url GELF_HTTP_URL GRAYLOG_GELF_HTTP_URL gelf_tls GELF_TLS — otlp_endpoint OTLP_ENDPOINT GRAYLOG_OTLP_GRPC_ENDPOINT ============== ====================== ============================================

Plus the common CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY and PROXY.

Attributes:

Name Type Description
api_token Secret | None

REST API access token, sent as HTTP Basic <token>:token; wins over username/password.

username str | None

REST user name for HTTP Basic auth.

password Secret | None

REST password.

gelf_host str

GELF host (default: the host of url).

gelf_port int | None

GELF port; None means 12202 for HTTP and 12201 otherwise (see :meth:gelf_port_for).

gelf_protocol GelfProtocol

default GELF transport (udp, tcp, http); default tcp.

gelf_http_url str | None

full GELF HTTP endpoint (default http(s)://<gelf_host>:<port>/gelf).

gelf_tls bool

TLS for GELF TCP (and https for the default GELF HTTP URL), with tls.

otlp_endpoint str | None

OTLP gRPC endpoint of a Graylog OpenTelemetry input (default http://<gelf_host>:4317).

requested_by str

value of the X-Requested-By header on non-GET requests.

authorization_header

authorization_header() -> str | None

Authorization value: Basic <token>:token or Basic <user>:<password>.

gelf_http_endpoint

gelf_http_endpoint() -> str

The effective GELF HTTP endpoint.

gelf_port_for

gelf_port_for(protocol: GelfProtocol | None = None) -> int

The GELF port for protocol: :attr:gelf_port, else 12202 (HTTP) / 12201.

known_secrets

known_secrets() -> list[str]

Credential values (and their Basic encodings) to redact from errors and logs.

otlp_grpc_endpoint

otlp_grpc_endpoint() -> str

The effective OTLP gRPC endpoint.

validate

validate() -> _C

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

with_options

with_options(**changes: Any) -> _C

A validated copy with some fields replaced (gelf_host follows a new url).

GraylogInput dataclass

A configured input (GET /api/system/inputs).

GraylogLogQueryClient

Bases: _QueryBase, BaseLogQueryClient

LogQueryClient on top of :meth:GraylogClient.search.

Absolute time range (default: the last hour), timestamp order (ties broken by gl2_message_id), offset cursors, hits normalised into log records. Graylog has no streaming API: :meth:tail polls every 2 s with a 10 s look-back window.

Parameters:

Name Type Description Default
client GraylogClient

the Graylog client.

required
streams Sequence[str] | None

stream ids every search is limited to (default: every readable stream).

None
default_window_s float | timedelta

search window when start is not given (default 3600 s).

DEFAULT_WINDOW_S

list_labels

list_labels() -> list[str]

Every indexed field name.

list_streams

list_streams() -> list[str]

Titles of every stream (all pages).

search

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

Search records; cursor is the offset of the next page.

tail

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

Poll for new matching records every interval_s (default 2 s) on a thread.

Delivers each record once, oldest first, starting at start (default now). Each poll looks back :data:TAIL_OVERLAP_S before the newest record seen and drops duplicates by message id, so late records are delivered too. Search errors go to on_error and polling continues. Raises :class:CancelledError on a closed client.

GraylogMessage dataclass

A stored message (search hit or :meth:GraylogClient.get_message).

GraylogStream dataclass

A stream.

GraylogTail

Polling tail of :meth:GraylogLogQueryClient.tail (a daemon thread).

:meth:stop is idempotent; closing the client stops the tail too.

poll_once

poll_once() -> int

Run one poll; returns the number of delivered records.

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.

IndexSet dataclass

An index set (GET /api/system/indices/index_sets).

InputState dataclass

Runtime state of an input (GET /api/system/inputstates/{id}).

LogClient

Bases: Protocol

Synchronous log client (SPEC LogClient).

LogExporter

Bases: Protocol

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

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

LogHandler

Bases: Handler

:class:logging.Handler that forwards records to a log client.

Attributes: extra= fields, logger.name, code.filepath/code.function/ code.lineno, thread.name and exception.* for exc_info. Records from loggers in exclude_loggers (prefix match; defaults to the HTTP stack the exporters use) and from the SDK's own worker threads are skipped to avoid feedback loops. When a formatter is set, the formatted text is the body; otherwise record.getMessage().

LogInput dataclass

Convenience input for :meth:LogClient.send; defaults are filled by the client.

LogQueryClient

Bases: Protocol

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

LogRecord dataclass

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

from_json classmethod

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: GraylogError

Missing record (HTTP 404).

OtlpGrpcLogExporter

LogExporter for the Graylog OpenTelemetry (gRPC) input.

OTLP LogsService/Export over gRPC, gzip when the batch asks for it. Stored fields are otel_*; the query client normalises them back into log records.

Parameters:

Name Type Description Default
endpoint str

http://host:4317 (plaintext) or https://host:4317 (TLS).

required
bearer_token str | Secret | None

token configured on the input; sent as authorization: Bearer ….

None
headers Mapping[str, str] | None

extra gRPC metadata.

None
tls TlsConfig | None

CA bundle and client certificate for https endpoints (insecure_skip_verify is not supported by gRPC and is ignored).

None
timeout_s float

deadline of one export call (default 30 s).

30.0
connect_timeout_s float

how long the first call waits for the channel (default 10 s).

10.0

Raises:

Type Description
ConfigError

for a bad endpoint or when grpcio is not installed.

export

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

Send one batch; raises the mapped SDK error when the call fails.

shutdown

shutdown() -> None

Close the channel (idempotent).

OtlpPartialSuccess

Partial success of an ExportLogsServiceResponse.

PermissionDeniedError

Bases: GraylogError

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: GraylogError

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

SearchResult dataclass

Result of :meth:GraylogClient.search / :meth:GraylogClient.search_relative.

SearchSort dataclass

Sort order of search results.

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.

StreamPage dataclass

One page of GET /api/streams/paginated.

StreamRule dataclass

A stream rule.

type: 1 exact, 2 regex, 3 greater, 4 smaller, 5 presence, 6 contain, 7 always, 8 input.

SystemInfo dataclass

GET /api/system (:meth:GraylogClient.system_info).

ThreadedAsyncLogExporter

AsyncLogExporter that runs a synchronous :class:LogExporter in worker threads.

TimeoutError

Bases: GraylogError

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: GraylogError

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

UnsupportedError

Bases: GraylogError

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

ValidationError

Bases: GraylogError

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.

current_trace_context

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

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

decode_export_logs_response

decode_export_logs_response(data: bytes) -> OtlpPartialSuccess

Decode partial_success; zero values when absent or malformed.

encode_export_logs_request

encode_export_logs_request(records: Sequence[LogRecord], *, scope_name: str = _SCOPE_NAME, scope_version: str = __version__) -> bytes

Encode records as an OTLP ExportLogsServiceRequest, one ResourceLogs per resource.

encode_gelf_udp

encode_gelf_udp(payload: bytes, *, compression: GelfCompression = 'gzip', chunk_size: int = DEFAULT_UDP_CHUNK_SIZE, message_id: bytes | None = None) -> list[bytes]

Compress (optional) and split a GELF payload into datagrams.

One datagram when it fits chunk_size, else chunks 0x1e 0x0f | id(8) | seq | count | data. Raises :class:ValidationError when more than 128 chunks would be needed.

error_for_code

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

Return the error class for a code (ErrorCode member or wire value).

error_for_grpc_status

error_for_grpc_status(status: int, message: str) -> ServiceError

Map a gRPC status code to the SDK error (OTLP retryable codes are retryable).

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.

flatten_attributes

flatten_attributes(attributes: Mapping[str, AttrValue], prefix: str = '') -> Iterator[tuple[str, AttrValue]]

Flatten nested mappings into dotted keys; lists and scalars are leaves.

format_timestamp

format_timestamp(value: datetime) -> str

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

gelf_field_key

gelf_field_key(name: str) -> str

Map an attribute name to its GELF additional field key (decision 3).

_ prefix, every character outside [A-Za-z0-9_.-] becomes _, and id (reserved by GELF) becomes _attr_id.

gelf_field_value

gelf_field_value(value: Any) -> GelfFieldValue | None

Map an attribute value to its GELF form (decision 3).

Strings and finite numbers unchanged, booleans → "true"/"false", None → omitted (None), non-finite numbers → their text, datetimes → ISO-8601, lists and mappings → compact JSON strings.

gelf_level_to_severity

gelf_level_to_severity(level: float) -> Severity

Syslog level → OTel severity: 0-2 → FATAL, 3 → ERROR, 4 → WARN, 5-6 → INFO, 7 → DEBUG.

get_logger

get_logger() -> logging.Logger

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

log_record_from_message

log_record_from_message(fields: Mapping[str, Any]) -> LogRecord

Normalise a stored Graylog message (search hit or get_message fields) into a record.

OTLP fields (otel_*) win over GELF fields. source → resource["host.name"], known resource fields (:data:RESOURCE_FIELDS) and otel_resource_attributes_* → resource, attr_id → id, otel_attributes_* and every other field except gl2_* and the reserved ones → attributes.

new_idempotency_key

new_idempotency_key() -> str

A random key for the Idempotency-Key header.

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_gelf_protocol

parse_gelf_protocol(value: str) -> GelfProtocol | None

Parse a GELF protocol name (case-insensitive); None when unknown.

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.

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.

severity_to_gelf_level

severity_to_gelf_level(severity: Severity | int) -> GelfLevel

OTel severity → syslog level: TRACE/DEBUG → 7, INFO → 6, WARN → 4, ERROR → 3, FATAL → 2.

Numbers between the named values use the band they fall into.

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.

tls_context

tls_context(tls: TlsConfig) -> ssl.SSLContext

An :class:ssl.SSLContext for the GELF TCP transport (CA bundle, client cert, skip).

to_attr_value

to_attr_value(value: Any) -> AttrValue

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

to_gelf_timestamp

to_gelf_timestamp(value: datetime) -> float

Unix seconds with millisecond precision (naive datetimes are taken as UTC).

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_gelf_field_key

validate_gelf_field_key(key: str) -> str

Validate an explicit additional field key for :meth:GelfMessage.set_field.

Accepts name or _name and returns the _name wire key. Raises :class:ValidationError for keys outside [A-Za-z0-9_.-], empty keys and the reserved id.

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.