Class LokiClient

java.lang.Object
codes.grow.packages.loki.LokiClient
All Implemented Interfaces:
AutoCloseable

public final class LokiClient extends Object implements 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.

  • Field Details

    • TENANT_HEADER

      public static final String TENANT_HEADER
      Tenant header.
      See Also:
    • ENCODING_FLAGS_HEADER

      public static final String ENCODING_FLAGS_HEADER
      Header that switches query responses to categorized labels.
      See Also:
  • Method Details

    • create

      public static LokiClient create(LokiConfig config)
      Creates a client.
      Parameters:
      config - validated configuration
      Returns:
      a new client
      Throws:
      ConfigException - when TLS or proxy settings are invalid
    • fromEnv

      public static LokiClient fromEnv()
      Creates a client from GROW_GRAFANA_LOKI_* and LOKI_* environment variables.
      Returns:
      a new client
    • builder

      public static LokiClient.Builder builder()
      Starts a client builder.
      Returns:
      a new builder
    • config

      public LokiConfig config()
      Returns the configuration.
      Returns:
      the configuration
    • transport

      public HttpTransport transport()
      Returns the HTTP transport, for service modules built on this client.
      Returns:
      the transport
    • tenantId

      public Optional<String> tenantId()
      Returns the tenant sent as X-Scope-OrgID.
      Returns:
      the tenant id, or empty
    • guard

      public CardinalityGuard guard()
      Returns the cardinality guard built from LokiConfig.allowedLabels().
      Returns:
      the guard
    • register

      public void register(AutoCloseable resource)
      Registers a resource (batch processor, log client) closed with the client.
      Parameters:
      resource - the resource
    • withTenant

      public LokiClient withTenant(String id)
      Returns a client for another tenant: it shares this client's connections and sends X-Scope-OrgID: id on 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

      public HealthStatus health()
      Readiness: GET /ready (with the configured auth and tenant headers). 200 ready → healthy ok; 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

      public CompletableFuture<HealthStatus> healthAsync()
      Asynchronous health().
      Returns:
      a future with the health status
    • ready

      public boolean ready()
      Returns whether GET /ready answers 200 (same probe as health()).
      Returns:
      true when ready
    • readyAsync

      public CompletableFuture<Boolean> readyAsync()
      Asynchronous ready().
      Returns:
      a future with the readiness
    • ping

      public Duration ping()
      Authenticated round trip: GET /loki/api/v1/labels?since=5m with auth and tenant headers.
      Returns:
      the latency
      Throws:
      AuthenticationException - without a tenant (multi-tenant Loki) or with wrong gateway credentials
    • pingAsync

      public CompletableFuture<Duration> pingAsync()
      Asynchronous ping().
      Returns:
      a future with the latency
    • buildInfo

      public BuildInfo buildInfo()
      Build information: GET /loki/api/v1/status/buildinfo.
      Returns:
      the build information
    • buildInfoAsync

      public CompletableFuture<BuildInfo> buildInfoAsync()
      Asynchronous buildInfo().
      Returns:
      a future with the build information
    • serverVersion

      public String serverVersion()
      Returns the server version (buildInfo().version(), e.g. 3.7.10).
      Returns:
      the version string
      Throws:
      UnsupportedException - when the server reports none
    • serverVersionAsync

      public CompletableFuture<String> serverVersionAsync()
      Asynchronous serverVersion().
      Returns:
      a future with the version
    • push

      public void push(List<LokiStream> streams)
      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

      public void push(List<LokiStream> streams, PushOptions options)
      Pushes streams (POST /loki/api/v1/push). JSON by default (optionally gzip); PushFormat.PROTOBUF sends a Snappy-compressed PushRequest. The cardinality guard moves labels outside LokiConfig.allowedLabels() to structured metadata (unless LokiConfig.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-retryable LokiServerException.
      Parameters:
      streams - streams (streams without entries are skipped)
      options - wire format and compression
    • pushAsync

      public CompletableFuture<Void> pushAsync(List<LokiStream> streams, PushOptions options)
      Parameters:
      streams - streams
      options - wire format and compression
      Returns:
      a future completing when Loki accepted the push
    • pushOtlp

      public void pushOtlp(List<LogRecord> records)
      Pushes records as OTLP/JSON to POST /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

      public void pushOtlp(List<LogRecord> records, boolean gzip)
      Pushes records as OTLP/JSON, optionally gzip-compressed.
      Parameters:
      records - records
      gzip - whether to gzip the body
    • pushOtlpAsync

      public CompletableFuture<Void> pushOtlpAsync(List<LogRecord> records, boolean gzip)
      Parameters:
      records - records
      gzip - whether to gzip the body
      Returns:
      a future completing when Loki accepted the records
    • query

      public QueryResult query(String logql)
      Instant metric query at the current time.
      Parameters:
      logql - metric query
      Returns:
      the result (vector or scalar)
      See Also:
    • query

      public QueryResult query(String logql, QueryOptions options)
      Instant metric query: GET /loki/api/v1/query. A log selector ({...} with or without a pipeline) is rejected with ValidationException: Loki does not run log queries as instant queries; use queryRange(java.lang.String) instead.
      Parameters:
      logql - metric query
      options - evaluation time (limit and direction are kept for API parity)
      Returns:
      the result
    • queryAsync

      public CompletableFuture<QueryResult> queryAsync(String logql, QueryOptions options)
      Parameters:
      logql - metric query
      options - options
      Returns:
      a future with the result
    • queryRange

      public QueryResult queryRange(String logql)
      Range query over the last hour (newest first, server default limit 100).
      Parameters:
      logql - log or metric query
      Returns:
      the result
      See Also:
    • queryRange

      public QueryResult queryRange(String logql, QueryRangeOptions options)
      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). end is exclusive.
      Parameters:
      logql - log or metric query
      options - window, step, limit (1–5000), direction
      Returns:
      the result (streams or matrix)
    • queryRangeAsync

      public CompletableFuture<QueryResult> queryRangeAsync(String logql, QueryRangeOptions options)
      Parameters:
      logql - query
      options - options
      Returns:
      a future with the result
    • labels

      public List<String> labels()
      Label names of the server's default window.
      Returns:
      label names (empty when nothing matches)
    • labels

      public List<String> labels(LabelsOptions options)
      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

      public CompletableFuture<List<String>> labelsAsync(LabelsOptions options)
      Asynchronous labels(LabelsOptions).
      Parameters:
      options - options
      Returns:
      a future with the label names
    • labelValues

      public List<String> labelValues(String name)
      Values of one label in the server's default window.
      Parameters:
      name - label name
      Returns:
      values
    • labelValues

      public List<String> labelValues(String name, LabelsOptions options)
      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 name
      options - window and scoping selector
      Returns:
      values (empty when nothing matches)
    • labelValuesAsync

      public CompletableFuture<List<String>> labelValuesAsync(String name, LabelsOptions options)
      Parameters:
      name - label name
      options - options
      Returns:
      a future with the values
    • series

      public List<Map<String,String>> series(List<String> matchers)
      Series matching any of the selectors in the server's default window.
      Parameters:
      matchers - stream selectors (at least one)
      Returns:
      label sets
    • series

      public List<Map<String,String>> series(List<String> matchers, TimeRange range)
      Series matching any of the selectors: GET /loki/api/v1/series (repeated match[], OR). At least one non-blank matcher is required.
      Parameters:
      matchers - stream selectors
      range - time window
      Returns:
      label sets
    • seriesAsync

      public CompletableFuture<List<Map<String,String>>> seriesAsync(List<String> matchers, TimeRange range)
      Parameters:
      matchers - stream selectors
      range - time window
      Returns:
      a future with the label sets
    • indexStats

      public IndexStats indexStats(String query)
      Index statistics in the server's default window.
      Parameters:
      query - stream selector
      Returns:
      the statistics
    • indexStats

      public IndexStats indexStats(String query, TimeRange range)
      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 selector
      range - time window
      Returns:
      the statistics
    • indexStatsAsync

      public CompletableFuture<IndexStats> indexStatsAsync(String query, TimeRange range)
      Parameters:
      query - stream selector
      range - time window
      Returns:
      a future with the statistics
    • volume

      public QueryResult volume(String query)
      Ingested bytes per series in the server's default window.
      Parameters:
      query - stream selector
      Returns:
      a vector result
    • volume

      public QueryResult volume(String query, VolumeOptions options)
      Ingested bytes per series or label: GET /loki/api/v1/index/volume (vector result). Needs limits_config.volume_enabled: true; otherwise Loki returns an empty vector ("no data", not an error).
      Parameters:
      query - stream selector
      options - window, limit, target labels, grouping
      Returns:
      a vector result
    • volumeAsync

      public CompletableFuture<QueryResult> volumeAsync(String query, VolumeOptions options)
      Parameters:
      query - stream selector
      options - options
      Returns:
      a future with the result
    • volumeRange

      public QueryResult volumeRange(String query)
      Volume over time in the server's default window.
      Parameters:
      query - stream selector
      Returns:
      a matrix result
    • volumeRange

      public QueryResult volumeRange(String query, VolumeOptions options)
      Volume over time: GET /loki/api/v1/index/volume_range. Always a matrix: a vector answer (every series has one point) is converted to one-sample series.
      Parameters:
      query - stream selector
      options - window, step, limit, target labels, grouping
      Returns:
      a matrix result
    • volumeRangeAsync

      public CompletableFuture<QueryResult> volumeRangeAsync(String query, VolumeOptions options)
      Parameters:
      query - stream selector
      options - options
      Returns:
      a future with the result
    • formatQuery

      public String formatQuery(String logql)
      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

      public CompletableFuture<String> formatQueryAsync(String logql)
      Asynchronous formatQuery(String).
      Parameters:
      logql - query
      Returns:
      a future with the normalized query
    • tail

      public LokiTail tail(String logql, Consumer<TailFrame> onFrame)
      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

      public LokiTail tail(String logql, Consumer<TailFrame> onFrame, LiveTailOptions options)
      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 with LokiTail.stop() or close().
      Parameters:
      logql - log query
      onFrame - 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)
      Parameters:
      logql - log query
      onFrame - frame callback
      options - options
      Returns:
      a future with the open stream
    • logClient

      public BatchingLogClient logClient()
      A batching log client (JSON push, default batching and redaction).
      Returns:
      the log client, closed with this client
      See Also:
    • logClient

      public BatchingLogClient logClient(LokiLogClientOptions options)
      A batching LogClient that writes to this Loki (and tenant). Records go through redaction and, for push protocols, the cardinality guard; LogProtocol.OTLP uses /otlp/v1/logs instead. close() flushes and closes every log client created here.
      Parameters:
      options - protocol, batching, resource, redaction, allowlist
      Returns:
      the log client
    • logQueryClient

      public LokiLogQueryClient logQueryClient()
      A LogQueryClient (search, tail, listStreams, listLabels, waitForLog) on this Loki and tenant.
      Returns:
      the query client
    • isClosed

      public boolean isClosed()
      Returns whether close() was called.
      Returns:
      true once closed
    • close

      public void close()
      Flushes and closes log clients created by logClient(), stops open tails and releases connections (children from withTenant(java.lang.String) leave the shared connections open). Idempotent.
      Specified by:
      close in interface AutoCloseable
    • toString

      public String toString()
      Overrides:
      toString in class Object