Package codes.grow.packages.loki
Class LokiClient
java.lang.Object
codes.grow.packages.loki.LokiClient
- All Implemented Interfaces:
AutoCloseable
Client for Grafana Loki: push (JSON, protobuf + Snappy, OTLP), LogQL queries, labels, series,
index stats and volume, WebSocket tail, status, multi-tenancy and the logging category (
logClient(), logQueryClient()).
Implements SPEC section 2.4. Thread-safe; create one per endpoint and close it when done.
try (LokiClient client = LokiClient.fromEnv()) {
client.push(List.of(LokiStream.of(Map.of("service_name", "api"), LokiEntry.of("hello"))));
QueryResult r = client.queryRange("{service_name=\"api\"} |= \"hello\"");
}
Every I/O method has a blocking form and an …Async form returning CompletableFuture. Blocking forms raise LokiException subclasses; async forms fail with
them.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classBuilder that configures and creates a client in one chain. -
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic LokiClient.Builderbuilder()Starts a client builder.Build information:GET /loki/api/v1/status/buildinfo.AsynchronousbuildInfo().voidclose()Flushes and closes log clients created bylogClient(), stops open tails and releases connections (children fromwithTenant(java.lang.String)leave the shared connections open).config()Returns the configuration.static LokiClientcreate(LokiConfig config) Creates a client.formatQuery(String logql) Normalizes a LogQL query on the server (GET /loki/api/v1/format_query); useful to check builder output.formatQueryAsync(String logql) AsynchronousformatQuery(String).static LokiClientfromEnv()Creates a client fromGROW_GRAFANA_LOKI_*andLOKI_*environment variables.guard()Returns the cardinality guard built fromLokiConfig.allowedLabels().health()Readiness:GET /ready(with the configured auth and tenant headers).Asynchronoushealth().indexStats(String query) Index statistics in the server's default window.indexStats(String query, TimeRange range) Approximate index statistics:GET /loki/api/v1/index/stats.indexStatsAsync(String query, TimeRange range) AsynchronousindexStats(String, TimeRange).booleanisClosed()Returns whetherclose()was called.labels()Label names of the server's default window.labels(LabelsOptions options) Label names:GET /loki/api/v1/labels.labelsAsync(LabelsOptions options) Asynchronouslabels(LabelsOptions).labelValues(String name) Values of one label in the server's default window.labelValues(String name, LabelsOptions options) Values of one label:GET /loki/api/v1/label/{name}/values.labelValuesAsync(String name, LabelsOptions options) AsynchronouslabelValues(String, LabelsOptions).A batching log client (JSON push, default batching and redaction).logClient(LokiLogClientOptions options) A batchingLogClientthat writes to this Loki (and tenant).ALogQueryClient(search, tail, listStreams, listLabels, waitForLog) on this Loki and tenant.ping()Authenticated round trip:GET /loki/api/v1/labels?since=5mwith auth and tenant headers.Asynchronousping().voidpush(List<LokiStream> streams) Pushes streams as JSON (POST /loki/api/v1/push).voidpush(List<LokiStream> streams, PushOptions options) Pushes streams (POST /loki/api/v1/push).pushAsync(List<LokiStream> streams, PushOptions options) Asynchronouspush(List, PushOptions).voidPushes records as OTLP/JSON toPOST /otlp/v1/logs(Loki's OTLP endpoint).voidPushes records as OTLP/JSON, optionally gzip-compressed.pushOtlpAsync(List<LogRecord> records, boolean gzip) AsynchronouspushOtlp(List, boolean).Instant metric query at the current time.query(String logql, QueryOptions options) Instant metric query:GET /loki/api/v1/query.queryAsync(String logql, QueryOptions options) Asynchronousquery(String, QueryOptions).queryRange(String logql) Range query over the last hour (newest first, server default limit 100).queryRange(String logql, QueryRangeOptions options) Range query (logs or metrics):GET /loki/api/v1/query_range.queryRangeAsync(String logql, QueryRangeOptions options) AsynchronousqueryRange(String, QueryRangeOptions).booleanready()Returns whetherGET /readyanswers 200 (same probe ashealth()).Asynchronousready().voidregister(AutoCloseable resource) Registers a resource (batch processor, log client) closed with the client.Series matching any of the selectors in the server's default window.Series matching any of the selectors:GET /loki/api/v1/series(repeatedmatch[], OR).seriesAsync(List<String> matchers, TimeRange range) Asynchronousseries(List, TimeRange).Returns the server version (buildInfo().version(), e.g.AsynchronousserverVersion().Live tail with default options (Loki replays the last hour first).tail(String logql, Consumer<TailFrame> onFrame, LiveTailOptions options) Live tail over WebSocket (/loki/api/v1/tail).tailAsync(String logql, Consumer<TailFrame> onFrame, LiveTailOptions options) Asynchronoustail(String, Consumer, LiveTailOptions).tenantId()Returns the tenant sent asX-Scope-OrgID.toString()Returns the HTTP transport, for service modules built on this client.Ingested bytes per series in the server's default window.volume(String query, VolumeOptions options) Ingested bytes per series or label:GET /loki/api/v1/index/volume(vector result).volumeAsync(String query, VolumeOptions options) Asynchronousvolume(String, VolumeOptions).volumeRange(String query) Volume over time in the server's default window.volumeRange(String query, VolumeOptions options) Volume over time:GET /loki/api/v1/index/volume_range.volumeRangeAsync(String query, VolumeOptions options) AsynchronousvolumeRange(String, VolumeOptions).withTenant(String id) Returns a client for another tenant: it shares this client's connections and sendsX-Scope-OrgID: idon every request and on the tail handshake.
-
Field Details
-
TENANT_HEADER
Tenant header.- See Also:
-
ENCODING_FLAGS_HEADER
Header that switches query responses to categorized labels.- See Also:
-
-
Method Details
-
create
Creates a client.- Parameters:
config- validated configuration- Returns:
- a new client
- Throws:
ConfigException- when TLS or proxy settings are invalid
-
fromEnv
Creates a client fromGROW_GRAFANA_LOKI_*andLOKI_*environment variables.- Returns:
- a new client
-
builder
Starts a client builder.- Returns:
- a new builder
-
config
Returns the configuration.- Returns:
- the configuration
-
transport
Returns the HTTP transport, for service modules built on this client.- Returns:
- the transport
-
tenantId
Returns the tenant sent asX-Scope-OrgID.- Returns:
- the tenant id, or empty
-
guard
Returns the cardinality guard built fromLokiConfig.allowedLabels().- Returns:
- the guard
-
register
Registers a resource (batch processor, log client) closed with the client.- Parameters:
resource- the resource
-
withTenant
Returns a client for another tenant: it shares this client's connections and sendsX-Scope-OrgID: idon every request and on the tail handshake. This client is unchanged; closing the child does not close the shared connections.- Parameters:
id- tenant id- Returns:
- the tenant client
- Throws:
ValidationException- when the id is invalid
-
health
Readiness:GET /ready(with the configured auth and tenant headers).200 ready→ healthyok;503→ unhealthy with Loki's text (e.g.Ingester not ready: waiting for 15s after being ready); network errors →unreachable. Never throws except for cancellation and configuration errors.- Returns:
- the health status
- Throws:
CancelledException- when interrupted or closed
-
healthAsync
Asynchronoushealth().- Returns:
- a future with the health status
-
ready
public boolean ready()Returns whetherGET /readyanswers 200 (same probe ashealth()).- Returns:
- true when ready
-
readyAsync
Asynchronousready().- Returns:
- a future with the readiness
-
ping
Authenticated round trip:GET /loki/api/v1/labels?since=5mwith auth and tenant headers.- Returns:
- the latency
- Throws:
AuthenticationException- without a tenant (multi-tenant Loki) or with wrong gateway credentials
-
pingAsync
Asynchronousping().- Returns:
- a future with the latency
-
buildInfo
Build information:GET /loki/api/v1/status/buildinfo.- Returns:
- the build information
-
buildInfoAsync
AsynchronousbuildInfo().- Returns:
- a future with the build information
-
serverVersion
Returns the server version (buildInfo().version(), e.g.3.7.10).- Returns:
- the version string
- Throws:
UnsupportedException- when the server reports none
-
serverVersionAsync
AsynchronousserverVersion().- Returns:
- a future with the version
-
push
Pushes streams as JSON (POST /loki/api/v1/push).- Parameters:
streams- streams (streams without entries are skipped)- Throws:
ValidationException- for invalid labels or timestamps (client or server side)- See Also:
-
push
Pushes streams (POST /loki/api/v1/push). JSON by default (optionally gzip);PushFormat.PROTOBUFsends a Snappy-compressedPushRequest. The cardinality guard moves labels outsideLokiConfig.allowedLabels()to structured metadata (unlessLokiConfig.disableLabelGuard()), then labels are validated. Entries without a timestamp get "now". The whole request succeeds or fails. Retrying is safe: Loki drops entries identical to stored ones, so the push is retried on 5xx and network errors. Status 260 (ingestion blocked) raises a non-retryableLokiServerException.- Parameters:
streams- streams (streams without entries are skipped)options- wire format and compression
-
pushAsync
Asynchronouspush(List, PushOptions).- Parameters:
streams- streamsoptions- wire format and compression- Returns:
- a future completing when Loki accepted the push
-
pushOtlp
Pushes records as OTLP/JSON toPOST /otlp/v1/logs(Loki's OTLP endpoint). Loki promotes its default resource attributes (service.name,deployment.environment, …) to labels and stores everything else as structured metadata.- Parameters:
records- records (an empty list sends nothing)
-
pushOtlp
Pushes records as OTLP/JSON, optionally gzip-compressed.- Parameters:
records- recordsgzip- whether to gzip the body
-
pushOtlpAsync
AsynchronouspushOtlp(List, boolean).- Parameters:
records- recordsgzip- whether to gzip the body- Returns:
- a future completing when Loki accepted the records
-
query
Instant metric query at the current time.- Parameters:
logql- metric query- Returns:
- the result (vector or scalar)
- See Also:
-
query
Instant metric query:GET /loki/api/v1/query. A log selector ({...}with or without a pipeline) is rejected withValidationException: Loki does not run log queries as instant queries; usequeryRange(java.lang.String)instead.- Parameters:
logql- metric queryoptions- evaluation time (limit and direction are kept for API parity)- Returns:
- the result
-
queryAsync
Asynchronousquery(String, QueryOptions).- Parameters:
logql- metric queryoptions- options- Returns:
- a future with the result
-
queryRange
Range query over the last hour (newest first, server default limit 100).- Parameters:
logql- log or metric query- Returns:
- the result
- See Also:
-
queryRange
Range query (logs or metrics):GET /loki/api/v1/query_range. Streams carry indexed labels; structured metadata and parsed labels are per entry (the categorize-labels encoding is requested).endis exclusive.- Parameters:
logql- log or metric queryoptions- window, step, limit (1–5000), direction- Returns:
- the result (streams or matrix)
-
queryRangeAsync
AsynchronousqueryRange(String, QueryRangeOptions).- Parameters:
logql- queryoptions- options- Returns:
- a future with the result
-
labels
Label names of the server's default window.- Returns:
- label names (empty when nothing matches)
-
labels
Label names:GET /loki/api/v1/labels. Structured metadata keys are not labels.- Parameters:
options- window and scoping selector- Returns:
- label names (empty when nothing matches)
-
labelsAsync
Asynchronouslabels(LabelsOptions).- Parameters:
options- options- Returns:
- a future with the label names
-
labelValues
Values of one label in the server's default window.- Parameters:
name- label name- Returns:
- values
-
labelValues
Values of one label:GET /loki/api/v1/label/{name}/values. The name is validated client side (Loki answers unknown and invalid names with an empty result).- Parameters:
name- label nameoptions- window and scoping selector- Returns:
- values (empty when nothing matches)
-
labelValuesAsync
AsynchronouslabelValues(String, LabelsOptions).- Parameters:
name- label nameoptions- options- Returns:
- a future with the values
-
series
Series matching any of the selectors in the server's default window.- Parameters:
matchers- stream selectors (at least one)- Returns:
- label sets
-
series
Series matching any of the selectors:GET /loki/api/v1/series(repeatedmatch[], OR). At least one non-blank matcher is required.- Parameters:
matchers- stream selectorsrange- time window- Returns:
- label sets
-
seriesAsync
public CompletableFuture<List<Map<String,String>>> seriesAsync(List<String> matchers, TimeRange range) Asynchronousseries(List, TimeRange).- Parameters:
matchers- stream selectorsrange- time window- Returns:
- a future with the label sets
-
indexStats
Index statistics in the server's default window.- Parameters:
query- stream selector- Returns:
- the statistics
-
indexStats
Approximate index statistics:GET /loki/api/v1/index/stats. Reads the TSDB index only, so data still in the ingester counts after the next chunk flush.- Parameters:
query- stream selectorrange- time window- Returns:
- the statistics
-
indexStatsAsync
AsynchronousindexStats(String, TimeRange).- Parameters:
query- stream selectorrange- time window- Returns:
- a future with the statistics
-
volume
Ingested bytes per series in the server's default window.- Parameters:
query- stream selector- Returns:
- a vector result
-
volume
Ingested bytes per series or label:GET /loki/api/v1/index/volume(vector result). Needslimits_config.volume_enabled: true; otherwise Loki returns an empty vector ("no data", not an error).- Parameters:
query- stream selectoroptions- window, limit, target labels, grouping- Returns:
- a vector result
-
volumeAsync
Asynchronousvolume(String, VolumeOptions).- Parameters:
query- stream selectoroptions- options- Returns:
- a future with the result
-
volumeRange
Volume over time in the server's default window.- Parameters:
query- stream selector- Returns:
- a matrix result
-
volumeRange
Volume over time:GET /loki/api/v1/index/volume_range. Always a matrix: avectoranswer (every series has one point) is converted to one-sample series.- Parameters:
query- stream selectoroptions- window, step, limit, target labels, grouping- Returns:
- a matrix result
-
volumeRangeAsync
AsynchronousvolumeRange(String, VolumeOptions).- Parameters:
query- stream selectoroptions- options- Returns:
- a future with the result
-
formatQuery
Normalizes a LogQL query on the server (GET /loki/api/v1/format_query); useful to check builder output.- Parameters:
logql- query- Returns:
- the normalized query
- Throws:
ValidationException- when the query does not parse
-
formatQueryAsync
AsynchronousformatQuery(String).- Parameters:
logql- query- Returns:
- a future with the normalized query
-
tail
Live tail with default options (Loki replays the last hour first).- Parameters:
logql- log query (selector + pipeline)onFrame- receives every frame with entries- Returns:
- the open stream
- See Also:
-
tail
Live tail over WebSocket (/loki/api/v1/tail). Returns once connected; handshake errors raise (AuthenticationException,ValidationException, …). Auth, tenant and categorize headers go on the handshake. Only log queries (starting with a selector) can be tailed. Stop withLokiTail.stop()orclose().- Parameters:
logql- log queryonFrame- receives every frame with entries (on the WebSocket thread)options- replay start, limit, delay, callbacks- Returns:
- the open stream
-
tailAsync
public CompletableFuture<LokiTail> tailAsync(String logql, Consumer<TailFrame> onFrame, LiveTailOptions options) Asynchronoustail(String, Consumer, LiveTailOptions).- Parameters:
logql- log queryonFrame- frame callbackoptions- options- Returns:
- a future with the open stream
-
logClient
A batching log client (JSON push, default batching and redaction).- Returns:
- the log client, closed with this client
- See Also:
-
logClient
A batchingLogClientthat writes to this Loki (and tenant). Records go through redaction and, for push protocols, the cardinality guard;LogProtocol.OTLPuses/otlp/v1/logsinstead.close()flushes and closes every log client created here.- Parameters:
options- protocol, batching, resource, redaction, allowlist- Returns:
- the log client
-
logQueryClient
ALogQueryClient(search, tail, listStreams, listLabels, waitForLog) on this Loki and tenant.- Returns:
- the query client
-
isClosed
public boolean isClosed()Returns whetherclose()was called.- Returns:
- true once closed
-
close
public void close()Flushes and closes log clients created bylogClient(), stops open tails and releases connections (children fromwithTenant(java.lang.String)leave the shared connections open). Idempotent.- Specified by:
closein interfaceAutoCloseable
-
toString
-