How LogQL metric queries turn logs into metrics
LogQL metric queries apply range aggregation functions to log query results, and parsers can pull numeric sample values such as latency out of log lines. That lets you compute an error rate, a top N list of log sources or a latency percentile directly from logs already stored in Loki, without running a separate metrics pipeline for the same events. Teams reach for this when an application writes request outcomes or timings into logs but nobody instrumented a counter or histogram for them, or when a question is needed quickly and a metric does not yet exist. A metric query is evaluated over a time range, so a dashboard panel or an alert can ask how many lines matched in the last few minutes, and Loki returns a time series that Grafana plots like any other.
What it does not replace is equally important. Log-derived metrics are only as precise as the log lines that feed them, so a busy service that emits a line per request will make these queries scan a lot of data, and the results depend on the log format staying stable. For high-volume, long-lived signals such as service level indicators, an instrumented metric in Prometheus is still the better source, because it is cheap to store and query at any scale. Before you build a dashboard on a metric query, confirm the query cost on your cluster's largest time range, check that the labels you select on are the ones your stream design actually provides, and decide who owns the parser when the application log format changes.
Which metric query fits error rates, top talkers and latency
Error rate questions ask how many log lines match a failure pattern over a time window, usually compared with total traffic. In LogQL you start with a log selector, add a line filter for the error text, and wrap the result in a range vector aggregation such as count_over_time. Because the line filter runs before any parsing, this shape is usually the cheapest of the three.
- Illustrative count:
sum by (app) (count_over_time({namespace="payments"} |= "ERROR" [5m]))counts error lines per application in five-minute windows. - Illustrative rate:
sum by (app) (rate({namespace="payments"} |= "ERROR" [5m]))returns the per-second rate of the same lines. - Labels it depends on: a stable
namespaceorapplabel, so the stream selector narrows the data before the filter runs. - Parsers it does not need: plain line filters work on raw text, so no
jsonorlogfmtstage is required unless the error level sits in a field. - Ratio caveat: a true error rate divides errors by total requests, so pair the error query with a total count over the same range and check that both use the same selector.
Confirm with your own log format that the error text appears consistently in the lines you filter on, because a changed log message will silently lower the count.
Top talker questions ask which sources produce the most log lines, bytes or errors. The usual pattern wraps a count or rate in sum by to aggregate per label, then applies topk to keep the largest series. The result depends entirely on which labels exist on the streams, so this shape is sensitive to label design.
- Illustrative query:
topk(5, sum by (app) (count_over_time({cluster="prod"}[1h])))lists the five applications with the most lines in the last hour. - Labels it depends on: the
byclause can only group on labels that exist on the stream, soapp,namespaceorhostmust be set at ingestion. - Grouping cost: every extra
bylabel multiplies the number of series returned, so keep the grouping to the one or two labels that answer the question. - Structured metadata: values such as user or request IDs are usually not stream labels and need a parser or structured metadata to group on, which costs more at query time.
- Bounded results: Loki limits how many series a query can return, so a
topkover a high-cardinality label can fail even when the top result looks small.
Ask your platform team which labels are stream labels in your cluster before writing top-N queries, because a query that groups on a non-indexed value will not behave the same way.
Latency questions need a numeric value from each log line, such as a duration field. LogQL cannot compute percentiles from text alone. Instead, you extract the number with a parser, convert it with unwrap, and pass the result to a range function such as quantile_over_time. This shape depends on the log format more than the other two.
- Illustrative query:
quantile_over_time(0.99, {app="checkout"} | json | unwrap duration_ms [5m]) by (route)returns the 99th percentile of aduration_msfield per route. - Parser dependency: the field must be extracted with
json,logfmt,patternorregexpbeforeunwrapcan read it as a number. - Unit discipline: confirm whether the field is in milliseconds or seconds, and whether it is always numeric, because lines with missing or text values are dropped or produce errors.
- Cost on wide ranges: parsing every line across a long window is expensive, so narrow the selector and time range first.
- Averages versus percentiles:
avg_over_timeafterunwrapis cheaper to read but hides tail latency, which is usually what teams need.
Check a few raw lines against the query output before you publish a dashboard, since a wrong field name or unit produces plausible but incorrect percentiles.
A metric query that a dashboard or alert runs every few minutes repeats the same work against the same data. A recording rule evaluates the query on a schedule and stores the result as a time series, so panels and alerts read stored values instead of rescanning logs. Loki's ruler supports recording rules, and the decision to use one depends on how often the query runs and how wide its range is.
- Good candidates: error-rate and top-talker queries that feed multiple panels or alerts, evaluated on the same interval.
- Poor candidates: one-off investigations, where a stored series adds little and the query runs only once.
- Storage and evaluation cost: the ruler and the destination metrics backend both consume resources, so count the rules and their series before adding more.
- Label discipline: rules that group by high-cardinality labels create many stored series, so keep the grouping labels small.
- Ownership: name each rule, document its query and assign an owner, so a change to log format does not break silent metrics.
Before you move a query into a rule, confirm the destination backend, the evaluation interval and the retention you need for the resulting series with your platform team.
Writing a metric query step by step
This sequence takes a log question from a raw stream selector to a metric query that returns a bounded set of series at an acceptable cost. Each step ends with a check, so the query is proven before it reaches a dashboard or alert.
Confirm labels and stream selectors
Start in Grafana Explore against the correct tenant data source and run the bare stream selector, such as
{app="checkout", env="prod"}, over a short recent range. Confirm that the labels you select on are the ones your team actually uses, that the selector narrows to the intended streams, and that it includes at least one equality matcher. Check the series list in the log volume view before you go further. If the selector matches more streams than expected, tighten it now, because every later step inherits this scope.Add line filters before parsers
Add line filter expressions such as
|= "ERROR"directly after the selector, before any parser stage. Line filters discard non-matching lines early, so the parser and aggregation only process the lines you need. Run the partial query and compare the returned line count against what you expect from the log view. You are done when the filter removes most irrelevant lines without dropping the ones you want to count. Keep parsers such as| jsonor| logfmtafter this point, not before.Choose the range vector and outer aggregation
Wrap the filtered log query in a range aggregation such as
count_over_time(...[5m])orrate(...[5m]), then choose an outer aggregation such assum by (...)ortopk(...)to control which labels remain. Pick the range duration to match the question and the panel's step. Keep grouping labels to a small, known set so the result has a readable number of series. Confirm the output in the table view: each series should have the labels you grouped by and sensible values across the range.Check that sample values are numeric for unwrap
If the query needs latency or another numeric value, extract that field with a parser and then use
unwrapwith a numeric field, for example| json | unwrap duration_ms. Before adding the aggregation, inspect several sample lines in the log view and confirm the field is present on every matching line and always parses as a number. Look for units embedded in the value, empty fields and text such as "n/a". Lines that fail conversion are reported as errors rather than silently counted, so check the error count in the query results before trusting any percentile.Test result series counts and query cost
Run the complete metric query in Grafana Explore over the time range the dashboard will use. Count the returned series and confirm the number matches the grouping labels you chose, since unexpected label values in a grouping clause can multiply series. Check the query statistics Grafana shows for bytes processed and execution time. Ask your platform owner which per-tenant query limits apply to your cluster, because a query that succeeds once can still hit those limits under dashboard refresh. If the series count or cost is too high, return to the selector and grouping steps.
Add the query to a dashboard panel
Create a panel with this query, set its visualization type to suit the result (time series for rates and percentiles, table or bar gauge for top talkers), and set a legend that names the grouping labels. Load the dashboard at the ranges your team will actually use and confirm each panel renders without errors or timeouts. Record the query text, the grouping labels and the owner in the dashboard description so that later edits go through the same checks. The panel is ready when it returns the expected series at the agreed time ranges.
Decide whether to promote the query to a recording rule
If the dashboard or alert evaluates the same metric query repeatedly across many users or refresh cycles, consider storing it as a recording rule with Loki's ruler so the result is computed once and kept as a metric. Confirm that the query is stable, that its series count stays bounded, and that your team can run the ruler and the Prometheus-compatible backend it writes to. Ask your platform owner to confirm how recording rules are configured in your deployment before you change anything. The decision is complete when the team has either kept the ad hoc panel or created a rule with a named owner.
Metric query options and when each fits
This table compares the range functions, outer aggregations and unwrap conversions you can use to turn Loki log lines into numbers, with the result shape and cost of each. Read each row as a choice: pick the function that matches the question you are answering, then check how much data it has to read before you put it on a dashboard.
| Option | What it returns | When it fits | Trade-off in result shape and cost |
|---|---|---|---|
| rate | Per-second log lines over the range, per series | Throughput or error rate per stream, such as errors per second from a selector with a line filter | Series are kept per label set, so many streams multiply output; reads every matching line in the range |
| count_over_time | Number of log lines in the range, per series | Total error counts over a window, such as errors in the last hour for an alert threshold | Same read cost as rate; output is a count rather than a rate, so the window size changes the number directly |
| bytes_over_time | Total bytes of log lines in the range, per series | Volume questions such as which service writes the most data, useful for ingestion cost planning | Measures raw line size, not a business quantity; a verbose service can outrank a busy but quiet one |
| bytes_rate | Bytes per second over the range, per series | Comparing data rates between sources on a graph where units should stay constant across window sizes | Same read cost as bytes_over_time; rate form is easier to compare across dashboards with different ranges |
| quantile_over_time | Quantile of unwrapped sample values over the range, per series | Latency percentiles such as p95 request duration parsed from a logfmt or json field with unwrap | Needs an unwrap expression; lines that fail to parse or lack the field are dropped, which can hide problems |
| sum (outer aggregation) | One total per remaining label set | Combining per-stream rates into a service or cluster figure for a graph or alert | Output shape collapses labels you do not list in by(); cheap on the result but still pays the range read underneath |
| topk (outer aggregation) | The N highest series at each step | Top talkers, such as the five noisiest applications or the endpoints with most errors | Returns a changing set of series over time, so a service can drop in and out of the chart; pick N and labels deliberately |
| avg (outer aggregation) | Mean of series values per label set | Average per-pod rate or average latency across instances when the sample values are already numeric | Averaging percentiles or quantiles across series gives a misleading figure; use quantile_over_time over the combined range instead |
| unwrap conversion functions | Numeric values taken from an extracted label, such as duration converted from text | Any sample-based metric; choose duration or bytes conversion so units match the field | Conversion errors show as dropped samples; confirm the field format in sample lines before building panels on it |
When to move a repeated metric query into a recording rule
A LogQL metric query runs against the stored log data every time it is evaluated, so the decision to move it into a recording rule is a decision about how often that evaluation happens and who depends on the result. Run the query on demand while it is exploratory, and store it once it has become a shared expression that many viewers or alerts depend on. A range vector aggregation such as a five-minute error rate over a busy tenant can read a large share of the chunks it selects on every refresh. Multiply that by several dashboard viewers with auto-refresh enabled and the query load becomes a standing cost on the read path, not a one-off investigation.
The signals that justify a recording rule are concrete and easy to check. Look for the same expression repeated across several dashboard panels, for alerting rules that evaluate an identical log-derived expression, and for panels whose slow load is visible in query timing and read volume. Also watch for expressions that a team cites in incident reviews, because those are the ones people will open under pressure. Recording rules write the result as a new time series through the ruler to a Prometheus-compatible backend, so the dashboard reads a precomputed series instead of rescanning logs. Confirm with your own cluster which backend and remote-write target you will use before you commit to this pattern, since the ruler configuration and its targets are covered in the Loki alerting and recording rules topic.
The trade-off has a cost on the other side. A stored series adds ingestion and storage on the metrics backend, it only reflects the labels and window you chose at creation time, and it drifts from the raw logs if the parsing logic changes. Keep an exploratory query in Explore until its shape is settled, then promote it, and record the owner, the window and the parser version alongside the rule. Ask your team to confirm the expected series count and retention in the metrics backend before the rule goes live, because a recording rule that keeps high-cardinality labels can add more load than the query it replaces.
How a metric query moves from logs to a panel or rule
The flow starts in Grafana or in Loki's ruler, which send a LogQL metric query to Loki's query path. Stream selectors and line filters first narrow which log chunks are read from object storage, so filtering early keeps reads small. Parsers and unwrap then turn matching lines into numeric samples, and the range aggregation returns series to a panel or to a recording rule that writes the results to a Prometheus-compatible backend. Check the selector and filter stages first when a metric looks wrong or slow, because every later stage only sees what they pass.
How a LogQL metric query narrows log data into numeric series.
Access and tenancy considerations for metric queries
Metric queries read the same tenant-scoped data as log queries, so a tenancy mistake or an open dashboard can expose more than the log lines themselves. The cards below cover where tenant identity is set, who sees derived counts, and how heavy metric queries affect shared capacity.
Tenant header set at the proxy
When auth_enabled is true, Loki identifies the tenant from the X-Scope-OrgID header on every request, including range queries that feed a dashboard panel. Metric queries inherit whatever tenant the caller sends. Your authenticating reverse proxy, such as nginx, HAProxy, OAuth2 Proxy or Pomerium, should set or overwrite this header from the verified identity, so a client cannot choose another tenant. Test that a user cannot query a tenant they do not belong to by sending a forged header through the proxy.
Loki multi-tenancy docsAuthentication sits outside Loki
Loki has no built-in authentication layer, so any request that reaches its HTTP port is trusted with whatever tenant it names. Put the authenticating proxy in front of every path that serves queries, including the query API used by Grafana data sources and any LogCLI access. Confirm that direct access to the Loki service from application networks is blocked at the network layer. Review this setup whenever a new route or ingress is added.
Loki authentication docsDerived counts reach users without log access
A dashboard built on count_over_time or rate can show error counts, top talkers or latency percentiles that a user could not see by reading the raw lines. If the log content is sensitive, these aggregates may still reveal customer activity, login failures or service health. Decide which teams may see metric panels, and confirm that Grafana folder and dashboard permissions match the tenant boundaries used for log queries.
Label-based access control needs Enterprise
Restricting which streams a user can read by label, so one team sees only its own namespaces, is a feature of Grafana Enterprise Logs, not open-source Loki. In open-source Loki, the practical boundary is the tenant, so teams that need finer separation within one tenant must either split tenants or accept shared visibility. Ask which model your compliance review expects before you design dashboards around it.
Enterprise Logs docsExpensive metric queries share capacity
A range vector query over many streams or a long time window reads a large volume of chunks, and that work runs on the same read path that serves other tenants. A dashboard refreshed by many users can therefore slow queries for everyone. Limit who can create broad metric panels, review query cost before publishing, and consider a recording rule for panels that many people load. Set per-tenant query limits so one tenant cannot consume the cluster.
Audit who reads metric data
Metric panels make it easy for many users to repeat the same expensive query, and the proxy and Grafana logs are where you can see who ran it. Record the authenticated identity, tenant and query path at the proxy, and keep Grafana audit settings enabled where your plan supports them. Review these records when a dashboard exposes data to a new group or when a tenant reports unexpected load.
Questions teams ask before writing metric queries
Is turning logs into metrics a few queries or a larger project?
For one service with consistent log lines, it is usually a small piece of work: a handful of range vector queries for error rates, top sources and latency. It grows when many teams want their own dashboards and alerts, when log formats differ between services, or when results must be stored and reviewed as recording rules. The number of distinct metrics, not the number of queries, is the main driver of scope. Ask any partner to list the metrics, owners and dashboards in writing before agreeing a fixed scope.
What makes LogQL metric queries take more effort to build?
Effort rises with inconsistent log formats, weak label design and the number of outputs. If one service writes JSON and another writes free text, each needs its own parser and tests. If labels hold high-cardinality values such as user IDs, queries become slow and hard to aggregate correctly. Each extra dashboard panel and alert rule also needs thresholds, a query check and a review with the people who will act on it. Consistent structure reduces all three.
What does our team need to provide before metric queries can be written?
Plan to provide representative log samples from each source, including normal lines, errors and slow requests. You will also need a current label inventory from Loki, showing which labels exist on which streams, and a description of which fields mean latency, status or customer. Grafana access with a role that can edit or create dashboards and rules is needed to test queries in place. Your team should also name an owner who can confirm which results are correct.
Can our own engineers write these LogQL metric queries without a partner?
Yes, if they know LogQL and have Grafana access to the cluster. Range vector functions such as rate and count_over_time are documented in the Loki metric queries reference, and latency percentiles use the unwrap syntax on a parsed numeric field. The harder work is agreeing definitions, such as what counts as an error, and keeping queries stable as log formats change. A partner is most useful when a short build must be done quickly, or when the team wants a documented, reviewed set of queries it can maintain.
How does the cost of metric queries depend on query frequency and data volume?
Cost is driven by how much data each query scans and how often it runs. A query over a three-hour window on a high-volume stream reads far more data than a narrow query on a small stream, and dashboards that refresh often multiply that load. Moving a repeated query into a recording rule shifts the cost to a scheduled evaluation that runs once and stores the result. Ask for the expected query count, dashboard refresh interval, log volume per stream and retention period in any quote, since these determine the infrastructure load.
What is a one-time cost and what recurs after metric queries are live?
The one-time cost covers analysis of log formats, writing and testing queries, building dashboards and agreeing definitions. Recurring work includes reviewing alerts, adjusting queries when applications change log output, watching query performance and keeping recording rules current. Infrastructure costs for storage and query capacity also recur. When you request a quote, ask which items are fixed-scope deliverables, which are retainer work and which the client keeps.
Do we need to change how our applications write logs first?
Not always, but consistent structured output makes metric queries simpler and more reliable. Logs written as JSON or logfmt let you extract fields with a parser, and a numeric field such as duration is needed for latency percentiles. If applications write unstructured text, the work may include agreeing a log format with the owning teams first. Any change to application logging should be tested in a non-production environment before it reaches production.
Does DeployOpen's work on this cover data security and compliance evidence?
Metric queries and dashboards can expose operational details, so access to them should follow your existing Grafana and tenant access model. DeployOpen can review who can read which streams and build queries that respect those boundaries. DeployOpen prepares systems and evidence for compliance assessments but does not issue audit reports or certifications. Independent auditors and certification bodies make those determinations.
How DeployOpen scopes LogQL metric work
DeployOpen scopes metric query work as a fixed-scope engagement that starts with the data, not the queries. The first step is reviewing the labels on your log streams and the formats of the log lines themselves, because label choices and parseable fields decide whether a rate(), count_over_time() or quantile_over_time() with unwrap is practical at all. We inventory which metrics your teams ask for (error rates per service, top talkers by source, latency percentiles per endpoint), check which of them can be answered from stream labels and which need a parser such as json or logfmt, and record the time ranges and dashboard refresh rates each one implies. The output of this step is a written list of candidate metrics with the labels and parsers each depends on, agreed with you before any query is written.
Next, DeployOpen writes the queries and validates them in your Grafana against your Loki data source, not in a sample environment. Validation covers whether results match a known-good count for a sample window, how long each query takes over the ranges your dashboards use, and how many series it returns. Where a query is repeated often enough to justify it, DeployOpen drafts the matching recording rule for your ruler, including the evaluation interval and the labels it keeps, and confirms the rule's output with you before deployment. Confirm with your platform team which Loki deployment mode and ruler setup you run, because that determines where the rules are stored and evaluated. The documentation for metric queries is the reference for function behavior: Loki metric queries documentation.
Every query and rule is documented in a handover pack: the purpose, the LogQL text, the labels and parsers it depends on, the expected cost profile, the owning team and the change process for updating it when log formats change. DeployOpen also offers optional retainers for ongoing tuning, such as reviewing query cost as log volume grows, adding metrics when new services ship, and retesting rules after Loki upgrades. Ask for the scope, deliverables, acceptance checks and any retainer terms in writing before work starts, and ask which of these items each quote includes.

