Skip to content

Loki

LogQL log and metric queries, log lines with pushdown, stream metadata and ruler state from Grafana Loki

Connector software
Free and open source
Service credentials
Required
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/loki/index.md to help me query Loki with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Find timeout errors in application logs

Replace the application label and time window with those used by your logs.

Uses your connected account. Set up the connector and credentials to run it with your data.

SELECT ts, pod, line
FROM loki.main.query_range('{app="checkout", level="error"} |= "timeout"', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY ts

Quick start

Choose where to run Loki, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach the release directly

Downloads the latest release for your platform and caches it locally.

ATTACH 'loki' AS loki (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/vgi-loki'
);

3. Add service credentials

After attaching, create the secret for the service you want to query in the same SQL session. Replace the placeholders with your service settings.

loki credentials

Connection to a Grafana Loki HTTP API (self-hosted Loki, Grafana Cloud Logs, or a Loki-compatible gateway).

Get these credentials →
secret.sql
CREATE SECRET loki (
    TYPE loki,
    base_url      '<base_url>',
    bearer_token  '<BEARER_TOKEN>',  -- secret
    username      '<username>',
    password      '<LOKI_PASSWORD>',  -- secret
    tenant_id     '<tenant_id>',
    extra_headers '<LOKI_EXTRA_HEADERS>'  -- secret
);
Credential fields and requirements →

4. Run a query

query.sql
SELECT ts, pod, line
FROM loki.main.query_range('{app="checkout", level="error"} |= "timeout"', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY ts
More example queries →
Technical details
Verified connector release
v0.2.0
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach the release directly

Uses the verified release each time you attach the connector.

ATTACH 'loki' AS loki (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/[email protected]'
);

Overview

Query Grafana Loki and Grafana Cloud Logs from DuckDB: LogQL log and metric queries as typed rows, log lines with SQL filters pushed into LogQL, stream metadata, ruler rules and alerts, and offline LogQL tools.

Catalog

Everything loki exposes once attached — read straight from the worker's released build.

loki 1 schema
main 19 functions

LogQL log and metric queries, pushdown log reads, stream metadata and ruler state from one Loki, plus offline LogQL tools.

Schema examples (34)
Examples (34)

Log lines per level for the checkout app in the hour before 01:00 UTC

SELECT labels['level'] AS level, value AS lines
FROM loki.main.query('sum by (level) (count_over_time({app="checkout"}[1h]))', time := TIMESTAMPTZ '2026-01-01 01:00:00+00')
ORDER BY level;

Current log volume per app in one namespace

SELECT labels['app'] AS app, round(value, 3) AS lines_per_second
FROM loki.main.query('sum by (app) (rate({namespace="shop"}[5m]))')
ORDER BY lines_per_second DESC;

Checkout error lines mentioning a timeout in a two-hour window

SELECT ts, pod, line
FROM loki.main.query_range('{app="checkout", level="error"} |= "timeout"', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY ts;

Checkout log lines per level in half-hour buckets, summed

SELECT labels['level'] AS level, sum(value) AS lines
FROM loki.main.query_range('sum by (level) (count_over_time({app="checkout"}[30m]))', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 02:00:00+00', step := 1800)
GROUP BY level
ORDER BY level;
30 more examples

Declined-payment errors per pod; app and level become stream matchers, the LIKE a |= line filter and the ts range the request window

SELECT pod, count(*) AS errors
FROM loki.main.logs('{namespace="shop"}')
WHERE app = 'checkout' AND level = 'error' AND line LIKE '%declined%' AND ts >= TIMESTAMPTZ '2026-01-01 00:00:00+00' AND ts < TIMESTAMPTZ '2026-01-01 02:00:00+00'
GROUP BY pod
ORDER BY pod;

The five newest checkout lines with a logfmt-parsed status; ORDER BY ts DESC LIMIT 5 becomes a backward query with limit 5

SELECT ts, parsed['status'] AS status, line
FROM loki.main.logs('{app="checkout"} | logfmt', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY ts DESC
LIMIT 5;

Which stream labels the shop namespace uses

SELECT label
FROM loki.main.labels(match := '{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY label;

How many distinct stream label names were seen in the last six hours

SELECT count(*) AS label_names FROM loki.main.labels();

Apps logging in the shop namespace

SELECT value AS app
FROM loki.main.label_values('app', match := '{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY app;

How many namespaces logged in the last six hours

SELECT count(*) AS namespaces FROM loki.main.label_values('namespace');

Stream cardinality per app in one namespace

SELECT app, count(*) AS streams
FROM loki.main.series('{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
GROUP BY app
ORDER BY streams DESC, app;

Which pods and levels the checkout app has streams for

SELECT labels['pod'] AS pod, level
FROM loki.main.series('{app="checkout"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY pod;

How much data a selector would read before running the query

SELECT streams, entries, bytes
FROM loki.main.index_stats('{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00');

Size of one app's logs over the last hour

SELECT round(bytes / 1e6, 1) AS megabytes
FROM loki.main.index_stats('{app="bulk"}');

Log volume per namespace, largest first

SELECT labels['namespace'] AS namespace, bytes
FROM loki.main.volume('{namespace=~".+"}', target_labels := 'namespace', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY bytes DESC, namespace;

The five noisiest apps in a namespace over the last hour

SELECT labels['app'] AS app, bytes
FROM loki.main.volume('{namespace="shop"}', target_labels := 'app', top_n := 5)
ORDER BY bytes DESC;

Fields inside the payments app's JSON lines, with types and parsers

SELECT field, type, cardinality, parsers
FROM loki.main.detected_fields('{app="payments"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY field;

logfmt fields in a namespace's recent lines, most distinct first

SELECT field
FROM loki.main.detected_fields('{namespace="shop"}')
WHERE list_contains(parsers, 'logfmt')
ORDER BY cardinality DESC;

Stream labels of one namespace by cardinality

SELECT label, cardinality
FROM loki.main.detected_labels(query := '{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY cardinality DESC, label;

High-cardinality stream labels over the last hour

SELECT label
FROM loki.main.detected_labels()
WHERE cardinality > 100
ORDER BY label;

The most frequent line shapes of one app

SELECT pattern, sum(count) AS lines
FROM loki.main.patterns('{app="bulk"}', start_date := TIMESTAMPTZ '2026-01-01 01:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
GROUP BY pattern
ORDER BY lines DESC;

Which patterns appear in the most five-minute buckets over the last hour

SELECT pattern, count(*) AS buckets
FROM loki.main.patterns('{namespace="shop"}', step := 300)
GROUP BY pattern
ORDER BY buckets DESC;

Every LogQL alerting rule with its state

SELECT group_name, rule_name, state, active_alerts
FROM loki.main.rules(rule_type := 'alert')
ORDER BY group_name, rule_name;

Which stream labels each rule's LogQL selects on

SELECT rule_name, loki.main.selector_labels(query) AS labels_used
FROM loki.main.rules()
ORDER BY rule_name;

Active LogQL alerts with severity

SELECT alert_name, state, labels['severity'] AS severity
FROM loki.main.alerts()
ORDER BY alert_name;

Firing alerts per severity

SELECT labels['severity'] AS severity, count(*) AS alerts
FROM loki.main.alerts()
WHERE state = 'firing'
GROUP BY severity
ORDER BY alerts DESC;

Which Loki version the server runs

SELECT version, revision FROM loki.main.build_info();

Whether the server is new enough for detected_fields()

SELECT version >= '3.0' AS has_detected_fields FROM loki.main.build_info();

Canonical form of a LogQL metric query

SELECT valid, formatted
FROM loki.main.format_query('sum(rate({app="x"}|="a"[5m]))by(b)');

The parser's message for an unclosed stream selector

SELECT valid, error FROM loki.main.format_query('{app="x" |= "a"');

Build a LogQL query from SQL strings with correct escaping

SELECT '{app=' || loki.main.logql_quote('checkout') || '} |= ' || loki.main.logql_quote('error="payment declined"') AS logql;

How many ruler rules are metric queries

SELECT loki.main.query_type(query) AS kind, count(*) AS rules
FROM loki.main.rules()
GROUP BY kind
ORDER BY kind;

The stream selectors every ruler rule reads

SELECT rule_name, unnest(loki.main.stream_selectors(query)) AS selector
FROM loki.main.rules()
ORDER BY rule_name;

Which stream labels the most rules depend on

SELECT l AS label, count(*) AS rules
FROM loki.main.rules(),
     unnest(loki.main.selector_labels(query)) u(l)
GROUP BY l
ORDER BY rules DESC;
Scalar functions
logql_quote (text VARCHAR) 2 examples

Quote a string as a LogQL string literal, escaping quotes, backslashes and control characters

Arguments
text VARCHAR
LogQL query text (for logql_quote: any string). NULL gives NULL.
ReturnsVARCHAR
Examples (2)

Build a LogQL query from SQL strings with correct escaping

SELECT '{app=' || loki.main.logql_quote('checkout') || '} |= ' || loki.main.logql_quote('error="payment declined"') AS logql;
SELECT s, loki.main.logql_quote(s) AS literal
FROM (VALUES ('plain'), ('say "hi"'), ('C:\temp'), ('a' || chr(9) || 'b')) t(s)
ORDER BY s;
Link
query_type (text VARCHAR) 2 examples

'log' for a LogQL log query, 'metric' for a metric query, NULL when the text does not lex

Arguments
text VARCHAR
LogQL query text (for logql_quote: any string). NULL gives NULL.
ReturnsVARCHAR
Examples (2)

How many ruler rules are metric queries

SELECT loki.main.query_type(query) AS kind, count(*) AS rules
FROM loki.main.rules()
GROUP BY kind
ORDER BY kind;
SELECT q, loki.main.query_type(q) AS kind
FROM (VALUES ('{app="x"} |= "err"'), ('sum by (app) (rate({app="x"}[5m]))'), ('{app="x"')) t(q)
ORDER BY q;
Link
selector_labels (text VARCHAR) 2 examples

Sorted distinct stream label names a LogQL query's selectors match on (NULL when the text does not lex)

Arguments
text VARCHAR
LogQL query text (for logql_quote: any string). NULL gives NULL.
ReturnsVARCHAR[]
Examples (2)

Which stream labels the most rules depend on

SELECT l AS label, count(*) AS rules
FROM loki.main.rules(),
     unnest(loki.main.selector_labels(query)) u(l)
GROUP BY l
ORDER BY rules DESC;
SELECT loki.main.selector_labels('sum(count_over_time({namespace="shop", app=~"check.*"} | json [5m])) / sum(count_over_time({namespace="shop"}[5m]))') AS labels;
Link
stream_selectors (text VARCHAR) 2 examples

Every stream selector ({...}) in a LogQL query, in order (NULL when the text does not lex)

Arguments
text VARCHAR
LogQL query text (for logql_quote: any string). NULL gives NULL.
ReturnsVARCHAR[]
Examples (2)

The stream selectors every ruler rule reads

SELECT rule_name, unnest(loki.main.stream_selectors(query)) AS selector
FROM loki.main.rules()
ORDER BY rule_name;
SELECT loki.main.stream_selectors('sum(rate({app="api", level="error"} | line_format "{{.msg}}" [5m])) / sum(rate({app="api"}[5m]))') AS selectors;
Link
Table functions
alerts (secret_name := VARCHAR) 2 examples

List the ruler's currently pending and firing alerts

Named arguments
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
alert_name VARCHAR
The alertname label.
state VARCHAR
'pending' or 'firing'.
active_at TIMESTAMP WITH TIME ZONE
When the alert became active (pending).
value DOUBLE
Value of the alert expression when last evaluated.
labels MAP(VARCHAR, VARCHAR)
Alert labels.
annotations MAP(VARCHAR, VARCHAR)
Alert annotations.
Examples (2)

Active LogQL alerts with severity

SELECT alert_name, state, labels['severity'] AS severity
FROM loki.main.alerts()
ORDER BY alert_name;

Firing alerts per severity

SELECT labels['severity'] AS severity, count(*) AS alerts
FROM loki.main.alerts()
WHERE state = 'firing'
GROUP BY severity
ORDER BY alerts DESC;
Link
build_info (secret_name := VARCHAR) 2 examples

Loki server version and build details

Named arguments
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
version VARCHAR
Server version, e.g. '3.7.0'.
revision VARCHAR
Source revision.
branch VARCHAR
Source branch.
build_user VARCHAR
Who built it.
build_date VARCHAR
Build date as reported.
go_version VARCHAR
Go toolchain version; NULL when not reported.
Examples (2)

Which Loki version the server runs

SELECT version, revision FROM loki.main.build_info();

Whether the server is new enough for detected_fields()

SELECT version >= '3.0' AS has_detected_fields FROM loki.main.build_info();
Link
detected_fields (query VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

Fields Loki detects in the lines of a log query, with type, cardinality and parser

Positional arguments
query VARCHAR
LogQL log query whose lines are sampled, e.g. '{app="payments"}'.
Named arguments
start_date := TIMESTAMP WITH TIME ZONE
Window start; default: one hour before end.
end_date := TIMESTAMP WITH TIME ZONE
Window end; default: now.
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
field VARCHAR
Field name, as a parser would extract it.
type VARCHAR
Inferred type: string, int, float, boolean, duration or bytes.
cardinality BIGINT
Approximate distinct values in the sampled lines.
parsers VARCHAR[]
Parsers that extract it (json, logfmt); empty for structured metadata.
json_path VARCHAR[]
Path inside a JSON line; empty for non-JSON fields.
Examples (2)

Fields inside the payments app's JSON lines, with types and parsers

SELECT field, type, cardinality, parsers
FROM loki.main.detected_fields('{app="payments"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY field;

logfmt fields in a namespace's recent lines, most distinct first

SELECT field
FROM loki.main.detected_fields('{namespace="shop"}')
WHERE list_contains(parsers, 'logfmt')
ORDER BY cardinality DESC;
Link
detected_labels (query := VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

Stream labels with their cardinality in a window

Named arguments
query := VARCHAR
Optional stream selector, e.g. '{namespace="shop"}'.
start_date := TIMESTAMP WITH TIME ZONE
Window start; default: one hour before end.
end_date := TIMESTAMP WITH TIME ZONE
Window end; default: now.
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
label VARCHAR
Stream label name.
cardinality BIGINT
Distinct values of the label in the window.
Examples (2)

Stream labels of one namespace by cardinality

SELECT label, cardinality
FROM loki.main.detected_labels(query := '{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY cardinality DESC, label;

High-cardinality stream labels over the last hour

SELECT label
FROM loki.main.detected_labels()
WHERE cardinality > 100
ORDER BY label;
Link
format_query (logql VARCHAR, secret_name := VARCHAR) 2 examples

Validate a LogQL query with the server's parser and return its canonical form

Positional arguments
logql VARCHAR
LogQL text to validate and format on the server.
Named arguments
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
valid BOOLEAN
Whether the server's LogQL parser accepts the query.
formatted VARCHAR
The query in the server's canonical form; NULL when invalid.
error VARCHAR
The parser's message (with line and column) when invalid; NULL when valid.
Examples (2)

Canonical form of a LogQL metric query

SELECT valid, formatted
FROM loki.main.format_query('sum(rate({app="x"}|="a"[5m]))by(b)');

The parser's message for an unclosed stream selector

SELECT valid, error FROM loki.main.format_query('{app="x" |= "a"');
Link
index_stats (query VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

Streams, chunks, entries and bytes a stream selector covers in a window

Positional arguments
query VARCHAR
Stream selector, e.g. '{namespace="shop"}'.
Named arguments
start_date := TIMESTAMP WITH TIME ZONE
Window start; default: one hour before end.
end_date := TIMESTAMP WITH TIME ZONE
Window end; default: now.
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
streams BIGINT
Streams matching the selector.
chunks BIGINT
Chunks those streams have in the window.
entries BIGINT
Log entries (lines) in those chunks.
bytes BIGINT
Uncompressed bytes of those chunks.
Examples (2)

How much data a selector would read before running the query

SELECT streams, entries, bytes
FROM loki.main.index_stats('{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00');

Size of one app's logs over the last hour

SELECT round(bytes / 1e6, 1) AS megabytes
FROM loki.main.index_stats('{app="bulk"}');
Link
label_values (label VARCHAR, match := VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

List the values of one stream label, optionally for matching streams

Positional arguments
label VARCHAR
Stream label name, e.g. 'app' or 'namespace'.
Named arguments
match := VARCHAR
Optional stream selector restricting which streams' values are listed.
start_date := TIMESTAMP WITH TIME ZONE
Window start; default: the server's (6 hours before end).
end_date := TIMESTAMP WITH TIME ZONE
Window end; default: now.
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
value VARCHAR
A value of the label.
Examples (2)

Apps logging in the shop namespace

SELECT value AS app
FROM loki.main.label_values('app', match := '{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY app;

How many namespaces logged in the last six hours

SELECT count(*) AS namespaces FROM loki.main.label_values('namespace');
Link
labels (match := VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

List the stream label names known to Loki, optionally for matching streams

Named arguments
match := VARCHAR
Optional stream selector restricting which streams' labels are listed, e.g. '{namespace="shop"}'.
start_date := TIMESTAMP WITH TIME ZONE
Window start; default: the server's (6 hours before end).
end_date := TIMESTAMP WITH TIME ZONE
Window end; default: now.
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
label VARCHAR
A stream label name present in the window.
Examples (2)

Which stream labels the shop namespace uses

SELECT label
FROM loki.main.labels(match := '{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY label;

How many distinct stream label names were seen in the last six hours

SELECT count(*) AS label_names FROM loki.main.labels();
Link
logs (selector VARCHAR, secret_name := VARCHAR, chunk_seconds := BIGINT, page_size := BIGINT, direction := VARCHAR, max_lines := BIGINT, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, label_columns := VARCHAR) +1 overload 2 examples
Positional arguments
selector VARCHAR
LogQL log query: a stream selector with an optional pipeline, e.g. '{namespace="shop"}' or '{app="api"} | json'. Omit it (or pass '{}') to build the selector entirely from WHERE filters on label columns.
Named arguments
secret_name := VARCHAR
Name of the loki secret to use when several exist.
chunk_seconds := BIGINT
The window is read in epoch-aligned chunks of this many seconds (matching Loki's split_queries_by_interval). · default 3600
page_size := BIGINT
Entries per request; must not exceed the server's max_entries_limit_per_query (5000 by default). · default 5000
direction := VARCHAR
Either 'backward' (newest first; the default) or 'forward' (oldest first). When omitted, ORDER BY ts [DESC] LIMIT n picks it.
max_lines := BIGINT
Stop after this many matching lines. NULL (default) reads every line; a SQL LIMIT also stops the scan early.
start_date := TIMESTAMP WITH TIME ZONE
Window start (inclusive) when not given by WHERE ts >= ...; default: one hour before the end, like Loki.
end_date := TIMESTAMP WITH TIME ZONE
Window end (exclusive) when not given by WHERE ts < ...; default: now.
label_columns := VARCHAR
Comma-separated extra stream labels to expose as their own columns (after job/namespace/pod/app/level) so WHERE filters on them push into the selector, e.g. 'cluster,service_name'. · default ""
Overloads
logs(selector VARCHAR, secret_name VARCHAR, chunk_seconds BIGINT, page_size BIGINT, direction VARCHAR, max_lines BIGINT, start_date TIMESTAMP WITH TIME ZONE, end_date TIMESTAMP WITH TIME ZONE, label_columns VARCHAR)logs(secret_name VARCHAR, chunk_seconds BIGINT, page_size BIGINT, direction VARCHAR, max_lines BIGINT, start_date TIMESTAMP WITH TIME ZONE, end_date TIMESTAMP WITH TIME ZONE, label_columns VARCHAR)
Returns columns
ts TIMESTAMP WITH TIME ZONE
Entry or sample timestamp (UTC, microsecond precision; ts_ns keeps nanoseconds).
ts_ns BIGINT
Entry timestamp in Unix nanoseconds (Loki's full precision).
job VARCHAR
Value of the 'job' label; NULL when absent.
namespace VARCHAR
Value of the 'namespace' label; NULL when absent.
pod VARCHAR
Value of the 'pod' label; NULL when absent.
app VARCHAR
Value of the 'app' label; NULL when absent.
level VARCHAR
Value of the 'level' label; NULL when absent.
cluster VARCHAR
Value of the 'cluster' label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the stream or series as MAP(VARCHAR, VARCHAR). Read one with labels['name'].
line VARCHAR
The log line as returned (after any line_format in the query).
structured_metadata MAP(VARCHAR, VARCHAR)
Structured metadata of the entry (e.g. trace_id, detected_level); empty map when none.
parsed MAP(VARCHAR, VARCHAR)
Labels extracted by parsers in the query (
Returns columns · depends on the arguments
ts TIMESTAMP WITH TIME ZONE
Entry or sample timestamp (UTC, microsecond precision; ts_ns keeps nanoseconds).
ts_ns BIGINT
Entry timestamp in Unix nanoseconds (Loki's full precision).
job VARCHAR
Value of the 'job' label; NULL when absent.
namespace VARCHAR
Value of the 'namespace' label; NULL when absent.
pod VARCHAR
Value of the 'pod' label; NULL when absent.
app VARCHAR
Value of the 'app' label; NULL when absent.
level VARCHAR
Value of the 'level' label; NULL when absent.
cluster VARCHAR
Value of the 'cluster' label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the stream or series as MAP(VARCHAR, VARCHAR). Read one with labels['name'].
line VARCHAR
The log line as returned (after any line_format in the query).
structured_metadata MAP(VARCHAR, VARCHAR)
Structured metadata of the entry (e.g. trace_id, detected_level); empty map when none.
parsed MAP(VARCHAR, VARCHAR)
Labels extracted by parsers in the query (
Examples (2)

Declined-payment errors per pod; app and level become stream matchers, the LIKE a |= line filter and the ts range the request window

SELECT pod, count(*) AS errors
FROM loki.main.logs('{namespace="shop"}')
WHERE app = 'checkout' AND level = 'error' AND line LIKE '%declined%' AND ts >= TIMESTAMPTZ '2026-01-01 00:00:00+00' AND ts < TIMESTAMPTZ '2026-01-01 02:00:00+00'
GROUP BY pod
ORDER BY pod;

The five newest checkout lines with a logfmt-parsed status; ORDER BY ts DESC LIMIT 5 becomes a backward query with limit 5

SELECT ts, parsed['status'] AS status, line
FROM loki.main.logs('{app="checkout"} | logfmt', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY ts DESC
LIMIT 5;
Link
patterns (query VARCHAR, step := DOUBLE, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

Detected log-line patterns and their counts per time bucket

Positional arguments
query VARCHAR
Stream selector, e.g. '{app="bulk"}'.
Named arguments
step := DOUBLE
Bucket width in seconds for the sample counts; default: the server's.
start_date := TIMESTAMP WITH TIME ZONE
Window start; default: one hour before end.
end_date := TIMESTAMP WITH TIME ZONE
Window end; default: now.
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
pattern VARCHAR
Detected log pattern; <_> marks a variable token.
level VARCHAR
Log level of the pattern's lines, when the server reports it.
ts TIMESTAMP WITH TIME ZONE
Start of the sample bucket.
count BIGINT
Lines matching the pattern in the bucket.
Examples (2)

The most frequent line shapes of one app

SELECT pattern, sum(count) AS lines
FROM loki.main.patterns('{app="bulk"}', start_date := TIMESTAMPTZ '2026-01-01 01:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
GROUP BY pattern
ORDER BY lines DESC;

Which patterns appear in the most five-minute buckets over the last hour

SELECT pattern, count(*) AS buckets
FROM loki.main.patterns('{namespace="shop"}', step := 300)
GROUP BY pattern
ORDER BY buckets DESC;
Link
query (logql VARCHAR, time := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

Evaluate a LogQL metric expression at one instant and return the result series as rows

Positional arguments
logql VARCHAR
LogQL metric expression, e.g. 'sum by (app) (count_over_time({namespace="shop"}[5m]))'. Log queries need query_range or logs.
Named arguments
time := TIMESTAMP WITH TIME ZONE
Evaluation time. Omit or NULL for the server's current time.
secret_name := VARCHAR
Name of the loki secret to use when several exist; default: the unscoped one.
Returns columns
result_type VARCHAR
LogQL result type: vector, matrix or scalar.
metric VARCHAR
The __name__ label; NULL for Loki results (kept so metric rows UNION with vgi-prometheus).
job VARCHAR
Value of the 'job' label; NULL when absent.
instance VARCHAR
Value of the 'instance' label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the stream or series as MAP(VARCHAR, VARCHAR). Read one with labels['name'].
ts TIMESTAMP WITH TIME ZONE
Entry or sample timestamp (UTC, microsecond precision; ts_ns keeps nanoseconds).
value DOUBLE
Sample value; NaN, +Inf and -Inf are kept.
histogram STRUCT of 3 fields
Always NULL for Loki; present so metric rows UNION with vgi-prometheus query_range.
STRUCT 3 fields
  • countDOUBLE
  • sumDOUBLE
  • bucketsSTRUCT[]
    STRUCT[] 5 fields
    • lowerDOUBLE
    • upperDOUBLE
    • countDOUBLE
    • lower_inclusiveBOOLEAN
    • upper_inclusiveBOOLEAN
string_value VARCHAR
Value of a string result; NULL otherwise.
Examples (2)

Log lines per level for the checkout app in the hour before 01:00 UTC

SELECT labels['level'] AS level, value AS lines
FROM loki.main.query('sum by (level) (count_over_time({app="checkout"}[1h]))', time := TIMESTAMPTZ '2026-01-01 01:00:00+00')
ORDER BY level;

Current log volume per app in one namespace

SELECT labels['app'] AS app, round(value, 3) AS lines_per_second
FROM loki.main.query('sum by (app) (rate({namespace="shop"}[5m]))')
ORDER BY lines_per_second DESC;
Link
query_range (logql VARCHAR, start_date TIMESTAMP WITH TIME ZONE, end_date TIMESTAMP WITH TIME ZONE, max_lines := BIGINT, direction := VARCHAR, step := DOUBLE, page_size := BIGINT, chunk_seconds := BIGINT, max_points_per_chunk := BIGINT, secret_name := VARCHAR) 2 examples

Run a LogQL log or metric query over a time range: log lines paged past the server limit, or metric series as long rows

Positional arguments
logql VARCHAR
LogQL log query (e.g. '{app="checkout"} |= "error"') or metric query (e.g. 'sum by (level) (count_over_time({app="checkout"}[5m]))').
start_date TIMESTAMP WITH TIME ZONE
Start of the range (inclusive).
end_date TIMESTAMP WITH TIME ZONE
End of the range: exclusive for log lines, the last evaluation time for metric queries.
Named arguments
max_lines := BIGINT
Log queries: stop after this many lines (Loki's limit). NULL (default) pages through every line in the range.
direction := VARCHAR
Log queries: 'backward' (newest first; the default) or 'forward' (oldest first). When omitted, ORDER BY ts [DESC] LIMIT n picks it.
step := DOUBLE
Metric queries: resolution step in seconds. NULL uses Loki's default, max(1, floor(range_seconds / 250)).
page_size := BIGINT
Log queries: entries per request; must not exceed the server's max_entries_limit_per_query (5000 by default). · default 5000
chunk_seconds := BIGINT
Log queries: the range is read in windows of this many seconds, aligned to the epoch like Loki's split_queries_by_interval. · default 3600
max_points_per_chunk := BIGINT
Metric queries: evaluation points per request (Loki rejects more than 11000). · default 11000
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
ts TIMESTAMP WITH TIME ZONE
Entry or sample timestamp (UTC, microsecond precision; ts_ns keeps nanoseconds).
ts_ns BIGINT
Entry timestamp in Unix nanoseconds (Loki's full precision).
job VARCHAR
Value of the 'job' label; NULL when absent.
namespace VARCHAR
Value of the 'namespace' label; NULL when absent.
pod VARCHAR
Value of the 'pod' label; NULL when absent.
app VARCHAR
Value of the 'app' label; NULL when absent.
level VARCHAR
Value of the 'level' label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the stream or series as MAP(VARCHAR, VARCHAR). Read one with labels['name'].
line VARCHAR
The log line as returned (after any line_format in the query).
structured_metadata MAP(VARCHAR, VARCHAR)
Structured metadata of the entry (e.g. trace_id, detected_level); empty map when none.
parsed MAP(VARCHAR, VARCHAR)
Labels extracted by parsers in the query (
result_type VARCHAR
LogQL result type: vector, matrix or scalar.
metric VARCHAR
The __name__ label; NULL for Loki results (kept so metric rows UNION with vgi-prometheus).
job VARCHAR
Value of the 'job' label; NULL when absent.
instance VARCHAR
Value of the 'instance' label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the stream or series as MAP(VARCHAR, VARCHAR). Read one with labels['name'].
ts TIMESTAMP WITH TIME ZONE
Entry or sample timestamp (UTC, microsecond precision; ts_ns keeps nanoseconds).
value DOUBLE
Sample value; NaN, +Inf and -Inf are kept.
histogram STRUCT of 3 fields
Always NULL for Loki; present so metric rows UNION with vgi-prometheus query_range.
STRUCT 3 fields
  • countDOUBLE
  • sumDOUBLE
  • bucketsSTRUCT[]
    STRUCT[] 5 fields
    • lowerDOUBLE
    • upperDOUBLE
    • countDOUBLE
    • lower_inclusiveBOOLEAN
    • upper_inclusiveBOOLEAN
string_value VARCHAR
Value of a string result; NULL otherwise.
Returns columns · depends on the arguments
ts TIMESTAMP WITH TIME ZONE
Entry or sample timestamp (UTC, microsecond precision; ts_ns keeps nanoseconds).
ts_ns BIGINT
Entry timestamp in Unix nanoseconds (Loki's full precision).
job VARCHAR
Value of the 'job' label; NULL when absent.
namespace VARCHAR
Value of the 'namespace' label; NULL when absent.
pod VARCHAR
Value of the 'pod' label; NULL when absent.
app VARCHAR
Value of the 'app' label; NULL when absent.
level VARCHAR
Value of the 'level' label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the stream or series as MAP(VARCHAR, VARCHAR). Read one with labels['name'].
line VARCHAR
The log line as returned (after any line_format in the query).
structured_metadata MAP(VARCHAR, VARCHAR)
Structured metadata of the entry (e.g. trace_id, detected_level); empty map when none.
parsed MAP(VARCHAR, VARCHAR)
Labels extracted by parsers in the query (
result_type VARCHAR
LogQL result type: vector, matrix or scalar.
metric VARCHAR
The __name__ label; NULL for Loki results (kept so metric rows UNION with vgi-prometheus).
job VARCHAR
Value of the 'job' label; NULL when absent.
instance VARCHAR
Value of the 'instance' label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the stream or series as MAP(VARCHAR, VARCHAR). Read one with labels['name'].
ts TIMESTAMP WITH TIME ZONE
Entry or sample timestamp (UTC, microsecond precision; ts_ns keeps nanoseconds).
value DOUBLE
Sample value; NaN, +Inf and -Inf are kept.
histogram STRUCT of 3 fields
Always NULL for Loki; present so metric rows UNION with vgi-prometheus query_range.
STRUCT 3 fields
  • countDOUBLE
  • sumDOUBLE
  • bucketsSTRUCT[]
    STRUCT[] 5 fields
    • lowerDOUBLE
    • upperDOUBLE
    • countDOUBLE
    • lower_inclusiveBOOLEAN
    • upper_inclusiveBOOLEAN
string_value VARCHAR
Value of a string result; NULL otherwise.
Examples (2)

Checkout error lines mentioning a timeout in a two-hour window

SELECT ts, pod, line
FROM loki.main.query_range('{app="checkout", level="error"} |= "timeout"', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY ts;

Checkout log lines per level in half-hour buckets, summed

SELECT labels['level'] AS level, sum(value) AS lines
FROM loki.main.query_range('sum by (level) (count_over_time({app="checkout"}[30m]))', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 02:00:00+00', step := 1800)
GROUP BY level
ORDER BY level;
Link
rules (rule_type := VARCHAR, secret_name := VARCHAR) 2 examples

List the ruler's LogQL recording and alerting rules with their health and state

Named arguments
rule_type := VARCHAR
Which rules: 'alert', 'record' or 'any'. · default "any"
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
group_name VARCHAR
Rule group name.
group_file VARCHAR
Namespace (file) the group belongs to.
group_interval_seconds DOUBLE
Group evaluation interval in seconds.
rule_name VARCHAR
Alert name or recorded metric name.
rule_type VARCHAR
'alerting' or 'recording'.
query VARCHAR
The rule's LogQL expression.
duration_seconds DOUBLE
Alerting rules: the 'for' duration in seconds; NULL for recording rules.
labels MAP(VARCHAR, VARCHAR)
Labels the rule adds.
annotations MAP(VARCHAR, VARCHAR)
Alerting rules: annotations; empty for recording rules.
health VARCHAR
'ok', 'err' or 'unknown'.
last_error VARCHAR
Last evaluation error; NULL when none.
state VARCHAR
Alerting rules: 'firing', 'pending' or 'inactive'; NULL for recording rules.
active_alerts BIGINT
Alerting rules: number of active (pending or firing) alerts; NULL for recording rules.
last_evaluation TIMESTAMP WITH TIME ZONE
Time of the rule's last evaluation; NULL if never evaluated.
evaluation_time_seconds DOUBLE
Duration of the last evaluation in seconds.
Examples (2)

Every LogQL alerting rule with its state

SELECT group_name, rule_name, state, active_alerts
FROM loki.main.rules(rule_type := 'alert')
ORDER BY group_name, rule_name;

Which stream labels each rule's LogQL selects on

SELECT rule_name, loki.main.selector_labels(query) AS labels_used
FROM loki.main.rules()
ORDER BY rule_name;
Link
series (match VARCHAR, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

List the streams (label sets) that match a selector in a time window

Positional arguments
match VARCHAR
Stream selector, e.g. '{namespace="shop"}'.
Named arguments
start_date := TIMESTAMP WITH TIME ZONE
Window start; default: the server's (6 hours before end).
end_date := TIMESTAMP WITH TIME ZONE
Window end; default: now.
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
job VARCHAR
The job stream label; NULL when absent.
namespace VARCHAR
The namespace stream label; NULL when absent.
pod VARCHAR
The pod stream label; NULL when absent.
app VARCHAR
The app stream label; NULL when absent.
level VARCHAR
The level stream label; NULL when absent.
labels MAP(VARCHAR, VARCHAR)
Every label of the stream.
Examples (2)

Stream cardinality per app in one namespace

SELECT app, count(*) AS streams
FROM loki.main.series('{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
GROUP BY app
ORDER BY streams DESC, app;

Which pods and levels the checkout app has streams for

SELECT labels['pod'] AS pod, level
FROM loki.main.series('{app="checkout"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY pod;
Link
volume (query VARCHAR, target_labels := VARCHAR, aggregate_by := VARCHAR, top_n := BIGINT, start_date := TIMESTAMP WITH TIME ZONE, end_date := TIMESTAMP WITH TIME ZONE, secret_name := VARCHAR) 2 examples

Bytes ingested per label set for a selector, largest first

Positional arguments
query VARCHAR
Stream selector, e.g. '{namespace=~".+"}'.
Named arguments
target_labels := VARCHAR
Comma-separated labels to aggregate by, e.g. 'namespace,app'; default: the selector's labels.
aggregate_by := VARCHAR
Either 'series' (one row per label combination) or 'labels' (one row per label name). · default "series"
top_n := BIGINT
Largest entries to return (the API's limit). · default 100
start_date := TIMESTAMP WITH TIME ZONE
Window start; default: one hour before end.
end_date := TIMESTAMP WITH TIME ZONE
Window end; default: now.
secret_name := VARCHAR
Name of the loki secret to use when several exist.
Returns columns
labels MAP(VARCHAR, VARCHAR)
The aggregated label set (or, with aggregate_by 'labels', the label name).
bytes BIGINT
Bytes ingested for that label set in the window.
Examples (2)

Log volume per namespace, largest first

SELECT labels['namespace'] AS namespace, bytes
FROM loki.main.volume('{namespace=~".+"}', target_labels := 'namespace', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY bytes DESC, namespace;

The five noisiest apps in a namespace over the last hour

SELECT labels['app'] AS app, bytes
FROM loki.main.volume('{namespace="shop"}', target_labels := 'app', top_n := 5)
ORDER BY bytes DESC;
Link

Credentials

The secret type loki declares, as reported by the worker itself.

loki

How to get these credentials

Connection to a Grafana Loki HTTP API (self-hosted Loki, Grafana Cloud Logs, or a Loki-compatible gateway).

secret.sql
CREATE SECRET loki (
    TYPE loki,
    base_url      '<base_url>',
    bearer_token  '<BEARER_TOKEN>',  -- secret
    username      '<username>',
    password      '<LOKI_PASSWORD>',  -- secret
    tenant_id     '<tenant_id>',
    extra_headers '<LOKI_EXTRA_HEADERS>'  -- secret
);
Key Type Required Description
base_url VARCHAR — Server root, e.g. 'http://loki:3100' or 'https://logs-prod-012.grafana.net'. /loki/api/v1/... is appended.
bearer_token secret VARCHAR — Token sent as 'Authorization: Bearer <token>'.
username VARCHAR — Basic-auth user name (Grafana Cloud Logs: the numeric instance id).
password secret VARCHAR — Basic-auth password (Grafana Cloud: an access-policy token with logs:read).
tenant_id VARCHAR — Tenant sent as the X-Scope-OrgID header (multi-tenant Loki).
extra_headers secret VARCHAR — Additional request headers as a JSON object, e.g. '{"X-Custom": "v"}'.

The worker doesn't mark which keys are required.

Needed by alertsbuild_infodetected_fieldsdetected_labelsformat_queryindex_statslabel_valueslabelslogspatternsqueryquery_range and 3 more functions

Create the secret in the same session, after attaching loki — the worker registers its secret types at ATTACH. Keys marked secret are masked in duckdb_secrets(); angle-bracket values are placeholders. Read credentials from your environment or secret store in your application and pass them through your SQL client’s parameter bindings. Keep real values out of saved SQL and history. Native DuckDB and Haybarn do not provide a SQL getenv() function.

Try these queries

Log lines per level for the checkout app in the hour before 01:00 UTC

SELECT labels['level'] AS level, value AS lines
FROM loki.main.query('sum by (level) (count_over_time({app="checkout"}[1h]))', time := TIMESTAMPTZ '2026-01-01 01:00:00+00')
ORDER BY level

Uses query

Checkout log lines per level in half-hour buckets, summed

SELECT labels['level'] AS level, sum(value) AS lines
FROM loki.main.query_range('sum by (level) (count_over_time({app="checkout"}[30m]))', TIMESTAMPTZ '2026-01-01 00:00:00+00', TIMESTAMPTZ '2026-01-01 02:00:00+00', step := 1800)
GROUP BY level
ORDER BY level

Uses query_range

Declined-payment errors per pod; app and level become stream matchers, the LIKE a |= line filter and the ts range the request window

SELECT pod, count(*) AS errors
FROM loki.main.logs('{namespace="shop"}')
WHERE app = 'checkout' AND level = 'error' AND line LIKE '%declined%' AND ts >= TIMESTAMPTZ '2026-01-01 00:00:00+00' AND ts < TIMESTAMPTZ '2026-01-01 02:00:00+00'
GROUP BY pod
ORDER BY pod

Uses logs

Which stream labels the shop namespace uses

SELECT label
FROM loki.main.labels(match := '{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY label

Uses labels

Apps logging in the shop namespace

SELECT value AS app
FROM loki.main.label_values('app', match := '{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
ORDER BY app

Uses label_values

Stream cardinality per app in one namespace

SELECT app, count(*) AS streams
FROM loki.main.series('{namespace="shop"}', start_date := TIMESTAMPTZ '2026-01-01 00:00:00+00', end_date := TIMESTAMPTZ '2026-01-01 02:00:00+00')
GROUP BY app
ORDER BY streams DESC, app

Uses series

31 more examples in the Catalog, each listed under the table or function it uses.

Questions it can answer

Plain-English questions from the worker's agent test tasks. An AI agent with this catalog attached should answer each one with SQL.

  • Using the loki worker, write the string say "hello" to C:\temp as a LogQL string literal.
  • How many error-level log lines did the checkout app write between 2026-01-01 00:00 and 02:00 UTC, per pod?
  • How many checkout error lines between 2026-01-01 00:00 and 02:00 UTC mention 'payment declined'?
  • List the bulk app's lines with status=failed between 2026-01-01 01:00 and 02:00 UTC, oldest first.
  • Count checkout log lines per level in 30-minute buckets between 2026-01-01 00:00 and 02:00 UTC.
  • Which apps logged in the shop namespace between 2026-01-01 00:00 and 02:00 UTC?

Loki is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.