Expand description
§grow-better-stack-logs
Rust SDK for Better Stack Logs by Grow Codes. Not affiliated with Better Stack, Inc.
Better Stack has two hosts with separate credentials: the source’s ingesting host
(source token, POST / with JSON / NDJSON / MessagePack, or OTLP /v1/logs) and the
SQL query host (ClickHouse HTTP interface with a connection’s username and password).
use grow_better_stack_logs::logging::{attrs, LogClient};
use grow_better_stack_logs::{BetterStackClient, LogClientOptions, SearchLogsOptions};
let client = BetterStackClient::from_env()?;
let logs = client.log_client(LogClientOptions::default())?;
logs.logger(None, attrs! {}).info("order placed", attrs! { "order_id" => 42 });
logs.flush(None).await?;
let found = client
.query()?
.search_logs(SearchLogsOptions::default().contains("order placed"))
.await?;
println!("{} records", found.records.len());
client.close().await;Features: blocking (a blocking client), testing (in-memory fakes and the conformance
runner), tracing-layer and log-bridge (logging adapters, on by default).
Re-exports§
pub use crate::core::Error;pub use crate::core::ErrorCode;pub use crate::core::HealthStatus;pub use crate::core::Result;pub use crate::core::RetryPolicy;pub use crate::core::Secret;
Modules§
- blocking
blocking - Blocking wrapper (feature
blocking). Each client owns a small tokio runtime (one worker thread, so batching log clients export in the background). - core
- Shared core: errors, configuration, secrets in config, redaction, retries and transport.
- logging
- Logging category (SPEC §4): records, batching, redaction, the
Loggerfacade, the query model and framework adapters. - testing
testing - Test support (feature
testing): in-memory fakes and the conformance runner (SPEC §6).
Macros§
- attrs
- Builds an
Attributesmap:attrs! { "user" => "ada", "n" => 3 }. - query_
params - Builds
QueryParams:query_params! { "needle" => "x", "n" => 3 }.
Structs§
- Better
Stack Client - Async client for Better Stack Logs. Cheap to clone (clones share the connections).
- Better
Stack Config - Immutable client configuration; build it with
BetterStackConfig::builderorBetterStackConfig::from_env.Debugoutput redacts every credential. - Better
Stack Config Builder - Builder for
BetterStackConfig. Values set here win over the environment. - Better
Stack LogExporter LogExporterfor Better Stack’s HTTP ingest API: maps records to events (to_better_stack_event), splits batches so no request exceeds 10 MiB, encodes them as JSON, NDJSON or MessagePack, gzips when asked and posts withAuthorization: Bearer <source token>. Exports are retried like idempotent calls (429, 5xx, network errors); Better Stack does not deduplicate, so an ambiguous failure may store a record twice.- Better
Stack Otlp LogExporter LogExporterthat sends OTLP/HTTP logs to the source’s ingesting host (POST {url}/v1/logs) with the source token. Records are grouped by resource; batches are split so no request exceeds the request limit;partial_successin the response counts as rejected records. Retried like idempotent calls (duplicates possible after an ambiguous failure).- Better
Stack Query - SQL query client for Better Stack Logs (ClickHouse HTTP interface with the connection’s own
Basic credentials). Implements
LogQueryClient:searchrunssearch_logson the configuredsource_table,tailpollssearch,list_streamsreturns the configured collection andlist_labelsisUNSUPPORTED(Better Stack has no labels). Cheap to clone. - Ingest
Exporter Options - Options of
BetterStackClient::new_exporter. - LogClient
Options - Options of
BetterStackClient::log_client. - Otlp
Exporter Options - Options of
BetterStackClient::new_otlp_exporter. - Otlp
Partial Success - Partial success reported by an OTLP response.
- Query
Options - Options of
BetterStackQuery::queryandBetterStackQuery::query_raw. - Search
Logs Options - Options of
BetterStackQuery::search_logs. - Send
Events Options - Options of
BetterStackLogExporter::send_events.
Enums§
- Encoding
- Wire encoding of ingest requests (
POST /on the ingesting host). - LogProtocol
- Wire protocol of
BetterStackClient::log_client. - Otlp
Protocol - OTLP/HTTP payload format.
- Query
Param - Value of a bound query parameter (
{name:Type}placeholder +param_<name>URL parameter).QueryParam::Nullis sent as\N(use aNullable(…)type).
Constants§
- DEFAULT_
SCOPE_ NAME - Default instrumentation scope name.
- DEFAULT_
SEARCH_ LIMIT - Default
limitof one search page. - DEFAULT_
URL - Empty on purpose: Better Stack has no global ingest host. Every source has its own ingesting
host (for example
https://s1234.eu-nbg-2.betterstackdata.com), so the ingest URL must be set whenever logs are sent (DECISIONS 4). - MAX_
RECORD_ BYTES - Better Stack limit for one record (10 MiB uncompressed).
- MAX_
REQUEST_ BYTES - Better Stack limit for one request body (10 MiB, measured compressed). The exporter never builds a larger uncompressed body, so the limit always holds.
- MAX_
SEARCH_ LIMIT - Largest
limitof one search page. - OTLP_
LOGS_ PATH - OTLP logs path on the ingesting host.
- VENDOR_
QUERY_ PASSWORD_ VARS - Vendor variables checked after
GROW_BETTER_STACK_LOGS_QUERY_PASSWORD. - VENDOR_
QUERY_ URL_ VARS - Vendor variables checked (in order) after
GROW_BETTER_STACK_LOGS_QUERY_URL. - VENDOR_
QUERY_ USERNAME_ VARS - Vendor variables checked after
GROW_BETTER_STACK_LOGS_QUERY_USERNAME. - VENDOR_
SOURCE_ TABLE_ VARS - Vendor variables checked after
GROW_BETTER_STACK_LOGS_SOURCE_TABLE. - VENDOR_
SOURCE_ TOKEN_ VARS - Vendor variables checked after
GROW_BETTER_STACK_LOGS_SOURCE_TOKEN. - VENDOR_
URL_ VARS - Vendor variables checked (in order) after
GROW_BETTER_STACK_LOGS_URL.
Functions§
- clickhouse_
code - Extracts the ClickHouse exception code from an error text (
Code: 60. DB::Exception: …). - code_
for_ clickhouse - The SDK error code for a ClickHouse exception code (API.md §5.1), or
Nonewhen the code has no special mapping (the HTTP status mapping applies then). - encode_
event - Encodes one raw event (a JSON object) for
encoding.VALIDATIONwhen it is not an object. - encode_
msgpack - Encodes a JSON value as MessagePack.
- encode_
otlp_ protobuf - Encodes an OTLP
ExportLogsServiceRequest(collector/logs/v1) as protobuf; records are grouped by resource, the scope isscope_namewith the SDK version. - encode_
record - Encodes one record as an event for
encoding: the JSON object for JSON/NDJSON, the MessagePack map (withdt/observed_dtas timestamp extensions) for MessagePack. - error_
for_ clickhouse - Builds the SDK error for a ClickHouse exception code, or
Nonewithout a special mapping.241(memory limit) gets a hint;202(too many simultaneous queries) is retryable. - escape_
param_ value - Escapes a
param_<name>value for ClickHouse, which parses query parameter values in the escaped (TabSeparated) text format: backslash →\\, tab →\t, newline →\n, carriage return →\r(DECISIONS 12). Without it the server would unescape a bound backslash. - format_
datetime64 YYYY-MM-DD HH:MM:SS.ffffff(UTC), theDateTime64(6)text form. Times before the epoch are clamped to it.- format_
event_ time - RFC 3339 UTC with nanoseconds (
2026-11-18T21:00:00.123456789Z), thedtform for JSON and NDJSON. Times before the epoch are clamped to it. - frame
- Joins encoded events into one request body.
- is_
valid_ identifier - Whether
sis a safe ClickHouse identifier (^[A-Za-z_][A-Za-z0-9_]*$), the rule for source tables (collections), which cannot be bound as SQL parameters. - json_
escape - JSON string escaping without the surrounding quotes, as in the raw event JSON.
- log_
record_ from_ row - Normalizes a
{dt, raw}row into aLogRecord(API.md §5.3):body=message(elsemsg, else the raw text), severity fromseverity_number/level/severity, trace ids fromspan.trace_id/span.span_id(or top-leveltrace_id/span_id),resourcefromresource, and every other field plusattributesintoattributes. - map_
ingest_ error - Maps ingest-host errors:
403(invalid or missing source token) →AUTHENTICATION,402(quota or spending limit) →RATE_LIMITEDwithretryable = false. Other errors pass through (406/413 are alreadyVALIDATION, 429/5xx follow SPEC §2.1). - map_
query_ error - Maps SQL-host errors by their ClickHouse code (found in the message), else keeps the error.
- normalize_
base_ url - Normalizes a host or URL: a value containing
://is used as given, a barehost[:port]becomeshttps://host[:port]; trailing slashes are removed. Blank input givesNone. - otlp_
json_ request - Builds the OTLP/JSON
ExportLogsServiceRequestobject. - parse_
datetime - Parses a ClickHouse
DateTime64text (2026-11-18 21:00:00.123456, UTC, 0–9 fraction digits), an RFC 3339 string (Zor numeric offset) or UNIX seconds / milliseconds. - parse_
partial_ success - Reads
partial_successfrom anExportLogsServiceResponse(protobuf or OTLP/JSON bytes). ReturnsNonewhen nothing was rejected or the body cannot be read. - parse_
rows - Parses a JSON-family response body (
JSONEachRow,JSON,JSONEachRowwithoutput_format_json_array_of_rows) into rows. A ClickHouse exception appended to the body is returned as the mapped error. - sql_
string - Escapes a value as a ClickHouse single-quoted string literal (
\,'and control characters escaped with a backslash). - to_
better_ stack_ event - Maps a record to the Better Stack event object (the JSON stored in the
rawcolumn):{dt, message, level, severity_number, span: {trace_id, span_id}, trace_flags, resource, attributes, observed_dt}.span.trace_id/span.span_idare Better Stack’s log ↔ trace correlation fields. Emptyresource/attributesare left out.
Type Aliases§
- Better
Stack Error - Service-prefixed alias of
Error. - Better
Stack LogClient - The batching
LogClientreturned byBetterStackClient::log_client. - Query
Params - Bound parameters of
BetterStackQuery::query: name → value. - Query
Row - One result row (JSON object; ClickHouse quotes 64-bit integers as strings).