LogQL parsers: json, logfmt, pattern and regexp

LogQL parsers pull fields out of log lines at query time. Choosing json or logfmt where possible, and pattern or regexp only for unusual lines, keeps queries fast and predictable on large time ranges.

On this page

When LogQL parsers decide whether your log queries stay fast

LogQL parsers extract fields from log lines at query time, so a team can filter and aggregate on values such as status codes or latency without changing how the application writes its logs. Parser choice matters because a parser runs against every line that survives the stream selector and line filters, and over a long time range that means reading a large volume of text. Loki supports json, logfmt, pattern, regexp and unpack parsers. Loki suggests json and logfmt when the log format allows it, and reserves pattern or regexp for lines with unusual structure, because structured formats let the parser move through the line with less work.

Before you commit a dashboard to a parser, confirm the actual line format from a sample of production logs, not from the logging library's documentation. A service that emits JSON in most paths but writes plain text on errors will need a parser strategy for both shapes, and a regexp that handles the rare shape can become the expensive part of every query. Narrow the time range and stream selector first, place line filters before parsers so Loki discards non-matching lines early, and test the query over the range your dashboards will actually use. Also note that labels produced by every LogQL parser are sanitized to follow the Prometheus metric name convention, so a field named http.status-code will appear under a different name than the one in the log. Plan field names with that rewrite in mind so alerts and dashboards reference the names Loki returns.

Parser decisions connect to the rest of the Loki LogQL querying hub: the query habits that keep dashboards responsive, the metric queries that build on extracted fields, and the query limits that stop an expensive parser run from reading too much data. Treat the parser as part of the query design you review with your team, and ask any implementation partner to show timings for representative long ranges before the parser choice is signed off.

Which parser fits which log format

This table compares the LogQL parsers by the log format each one handles, what it extracts, its relative cost on large time ranges and when it fits. Read it top to bottom: prefer json or logfmt whenever the log shape allows it, and fall back to pattern or regexp only for lines that have no consistent structure.

ParserLog format it handlesCost on large rangesWhen it fits
jsonLines that are valid JSON objects, including nested fieldsLower than regexp; parses structure rather than scanning textApplication logs that emit JSON. Use it first whenever the service can write JSON.
logfmtKey=value pairs separated by spacesLower than regexp; a single pass over known key syntaxGo and many infrastructure tools that write logfmt. Choose it when keys are consistent across lines.
patternLines with a fixed, repeated text layout and named capturesModerate; matches a template rather than arbitrary regular expressionsWeb server access logs or proxy lines with stable positions. Use when fields are in a predictable order without key names.
regexpIrregular or variable text where only a regular expression can locate fieldsHighest of the four; evaluates a regex on every line in rangeLegacy or mixed-format lines that pattern cannot match. Narrow the time range and add line filters first.
unpackLabels packed into the log entry by a log shipper such as Promtail or AlloyLow, since fields are already structured at ingestOnly when your shipper packs fields this way. Confirm the exact behavior in the Loki log queries documentation before relying on it.

How to add and verify a parser in a LogQL query

This sequence takes a parser from raw sample lines to a verified, narrowly scoped LogQL query that returns the fields you expect. Each step ends with a check so you know the extraction is correct before you widen the time range.

  1. Inspect sample lines in Grafana Explore

    Open Grafana Explore against the Loki data source for the tenant that owns the logs, select a stream with a stable stream selector, and read ten to twenty raw lines from a short recent window. Note whether each line is JSON, logfmt, or free text with a fixed layout, and whether the format changes between services or over time. Check is complete when you can describe the format of every line type you expect to query, including the lines that break the usual pattern.

  2. Choose the parser that matches the format

    Use the json or logfmt parser when lines are consistently structured in those formats, because they are the parsers Loki suggests when possible. Reach for pattern when lines have a fixed, unusual layout with delimiters you can name, and for regexp only when neither of the other options fits, since regular expressions are the most expensive to evaluate. Write down the parser choice and the reason. The check is that a single parser handles the sample lines you collected without errors in the Explore preview.

  3. Add line filters before the parser

    Place line filter expressions such as a substring match or a regular expression match ahead of the parser stage in the pipeline, so Loki discards non-matching lines before it spends time parsing them. Keep the filter as narrow as the question allows. The check is to compare the number of lines returned before and after adding the filter in a short range: the filtered query should return only the lines you intended, and the parser should not produce errors on lines that should have been excluded.

  4. Extract only the fields you need

    Add the parser expression and limit extraction to the fields the query uses, for example with a parser that names only the keys required for a filter or aggregation, rather than pulling every key from a large payload. Each extracted field becomes a label available to later stages, so extraction should match the question being asked. The check is that the parser error count stays at zero in the result view, and that the extracted field values look right on the sample lines you inspected in the first step.

  5. Confirm sanitized label names

    Look at the extracted label names in the query result and compare them with the original keys in the log lines. Labels produced by all LogQL parsers are sanitized to follow the Prometheus metric name convention, so a key containing dots, dashes or other characters is renamed. Record the sanitized form of each field you will reference later. The check is that every field name used in a later filter or aggregation matches the sanitized name exactly, because a mismatch returns no data without an error.

  6. Verify the series on a narrow time range

    Run the complete query over a short, recent window, such as the last few minutes of a busy stream, and confirm the returned series have the labels and values you expect. Count the series and compare them with what you saw in the raw lines. The check is that the series count and sample values match your manual reading of the lines, and that no parse error lines appear in the results. Keep the range narrow until this check passes.

  7. Widen the time range and recheck

    Only after the narrow check passes, extend the time range in steps and rerun the same query each time. Watch for parse errors on lines that appear in older or differently formatted data, and for a sharp rise in query time as the range grows, which signals that the parser is doing more work than the filters justify. The check is that the series remain correct across the wider window, and that you can state which format variants the query handles. Save the verified query only after this pass.

Why parser cost grows with the time range

Parser cost grows with the volume of log data a query reads, and that volume is set by the time range and the stream selector before any parser runs. A LogQL parser such as json, logfmt, pattern or regexp executes against every line that survives the stream selector and the line filters, so the work it does is proportional to how many lines reach it. Doubling the range roughly doubles the lines a parser must examine, which is why a query that feels instant over one hour can become slow over seven days even though the expression did not change.

The multiplication happens when a broad selector is combined with an expensive parser over a long range. Consider an illustrative case: a selector that matches every stream in a namespace, a regexp parser with several capture groups, and a 30-day range. The regular expression runs on each line in every matched stream, so the cost compounds across both the number of streams and the number of lines per stream. Narrowing the selector to the labels that identify the workload, or shortening the range to the window under investigation, reduces the input before the parser sees it. Check whether the selector is also the one Loki uses to pick chunks, because a selector that matches too much data is expensive even when the parser is cheap.

Order the pipeline so that each stage discards data before the next one does work: stream selector first, then line filters such as |= "timeout", then the parser, then label filters on extracted fields. Line filters are far cheaper than parsing because they test raw text, so a filter that drops most lines before the parser runs removes most of the parser's work. Verify the effect in your own environment rather than trusting a reordering on faith. Run the query with its query statistics visible in Grafana Explore or through LogCLI, compare bytes and lines processed before and after the change, and confirm the figures on your own data, since volume and selectivity differ widely between clusters.

How a parser step fits into the LogQL query path

The query starts with a stream selector, which uses labels to pick the streams Loki reads, so that choice decides how much data is scanned. Line filters then discard non-matching lines before any parser runs, and the parser step extracts fields from the survivors. Label filters act on those extracted fields, and the result returns to Grafana or LogCLI. The cost sits at the parser step, because it runs on every line that survived the earlier filters, so check that filters come first.

Where the parser sits in the LogQL query path and where cost accrues.

Security and data handling for parsed fields

Parsers turn log content into fields that can be filtered, graphed and shared, so whatever a parser can reach becomes visible to anyone who can query it. The cards below cover where sensitive values leak, how tenant boundaries and access control depend on your deployment, and who should be allowed to run costly parser queries.

Sensitive values extracted into labels

Parsers extract fields at query time, but a field promoted to a label through a label_format or keep step is stored as stream metadata and appears in label lists, dashboards and saved queries. Parsed values such as session tokens, email addresses or account numbers should never become labels. Review every parsed field name before it is promoted, and redact sensitive values at ingestion where possible, since query-time parsing cannot hide what was already stored in the log line.

Loki log queries docs

Sensitive values shown in dashboards

A parsed field displayed in a Grafana panel, table or Logs Drilldown view is visible to everyone who can open that panel, even when the raw line is hidden from them. Dashboards that group by user or card_last4 expose those values in legends, tooltips and exported data. Check each shared dashboard and panel table for parsed fields that carry personal or secret data, and restrict dashboard sharing to people who would be allowed to read the underlying lines.

Tenant boundaries across X-Scope-OrgID

With auth_enabled set to true, Loki separates data by the X-Scope-OrgID header sent on each request. Queries that combine several tenant IDs with a pipe separator read across tenants, so a parser query that runs against a multi-tenant data source can return fields from every tenant it covers. Confirm which tenant IDs each Grafana data source and LogCLI profile sends, and treat the header as an identifier, not a security control, because a client can set any value it likes.

Loki multi-tenancy docs

No built-in authentication layer

Loki does not authenticate users. Its documentation states that you must place an authenticating reverse proxy, such as nginx, HAProxy, OAuth2 Proxy or Pomerium, in front of it. Without that proxy, anyone who can reach the Loki HTTP port can run any LogQL query and set any tenant header. Confirm that the query endpoint is reachable only through the proxy, and that the proxy, not the client, decides which tenant IDs a user may send.

Loki authentication docs

Who may run expensive parser queries

Parsers run on every line that survives the stream selector and line filters, so a regexp or pattern query over a long time range can read large volumes and occupy query capacity for other users. Decide which roles may run unscoped parser queries, and which must go through saved, reviewed queries or dashboards. Ask your Loki operator which per-tenant query limits are set and whether query blocking rules exist for known costly patterns.

Access control depends on the deployment

Open-source Loki gives you tenant separation and whatever authentication your reverse proxy provides, but it does not offer label-based access control for query results. Grafana Enterprise Logs adds token authorization, label-based access control and cross-tenant queries, as its documentation describes. Before you promise a team that it cannot see a parsed field, confirm in writing which control enforces that restriction in your chosen deployment, and test it with a non-privileged account.

Grafana Enterprise Logs docs

Questions teams ask before parsing logs in Loki

Can our own team write LogQL parsers without outside help?

Yes, most teams with Grafana and Loki experience can write parsers for a small, well-understood set of log formats. Start with json or logfmt wherever your applications emit those formats, because they need no hand-written expressions. Reserve pattern and regexp for lines with unusual structure, and test each expression against a representative sample before it reaches a shared dashboard. The work becomes harder when many services log in different shapes, when parsers must be reviewed for cost on long time ranges, or when several teams query the same data. In those cases the effort lies less in the syntax and more in agreeing on field names, testing edge cases and keeping parsers stable across releases.

What makes the parser work larger or smaller?

Three factors drive the effort most. The first is log format consistency: services that already emit structured JSON or logfmt need little work, while free-text lines with varied layouts need many regular expressions and more testing. The second is the number of services and log sources, since each distinct format needs its own parser and its own sample set. The third is dashboard count: every panel or saved query that depends on an extracted field must keep working when a parser changes, so a large dashboard estate raises the cost of each change. Ask for a list of formats, sources and dashboards before requesting a quote, because those three counts shape most of the scope.

Does moving an application to a new log format change which parser we should use?

Yes. A format change can move a service from a regex-based parser to json or logfmt, which is usually cheaper to query and easier to maintain. The switch is not free, though. Dashboards, alerts and saved queries built on the old field names must be updated, and any label names extracted by the parser are sanitized to follow the Prometheus metric name convention, so a renamed field can change what appears in results. Run old and new formats side by side for a period, compare the extracted fields, and only then retire the old parser. Plan this with the teams that own the dashboards, not only the team that owns the application.

How long does a parser review usually take?

The duration depends on scope, and no fixed figure applies to every cluster. A review of a single service with consistent JSON output is typically a short exercise, while a review across many services, several formats and a large set of dashboards takes considerably longer. The main time sinks are collecting representative samples, agreeing on field names with dashboard owners and checking query performance on the time ranges people actually use. Ask any provider for the list of services, formats and dashboards in scope, the test ranges they will use and the points where they need your sign-off. A written scope turns a vague duration into one you can check.

What do we need to provide before parser work starts?

The work needs four inputs from your team. First, representative sample logs from each service, including malformed lines, multi-line entries and rare error messages, because those produce most parser failures. Second, access to the Grafana instance and the Loki data source with a role that can run Explore queries and edit dashboards in a non-production copy. Third, agreed test time ranges, such as a busy day and a quiet day, so cost and correctness are checked under realistic load. Fourth, a named owner who can approve field names. Without these inputs, parsers tend to be tested only on clean examples and then fail in production, so confirm each item with the people who run the logging pipeline.

What does parser cost look like on large time ranges?

Parser cost grows with the number of lines Loki must read and process, so a parser that is fast on a five-minute window can be slow across days. json and logfmt parse each line once and are generally cheaper than regexp or pattern, which scan content with more work per line. Placing line filters before parsers reduces the lines that reach the parser, and extracting only the fields you need keeps label sets small. Test expensive parsers on the widest range your dashboards use, watch query statistics, and ask whether an expression should become a recording rule if it runs repeatedly. These checks belong in the review, not after the dashboard is in use.

When is it worth bringing in a partner for Loki parsing?

Bring in a partner when the work spans many formats, several teams or a large dashboard estate, or when you need a documented result that another team can maintain. DeployOpen plans and implements self-hosted open-source platforms in infrastructure you control, including Grafana and Loki, and can scope parser work in writing before it starts. Keep the decision practical: if a single engineer can handle the formats in a few services, internal work may be enough. If formats are inconsistent, if production dashboards depend on fields you cannot change quickly, or if audit or compliance reviewers will ask how log fields are derived, a fixed written scope and clear handover usually justify outside help. Ask any provider to name the deliverables, tests and handover documents before you agree.

Choosing a parser by log structure

The decision starts with the raw log line. If the line is JSON, use the json parser. If it is a key=value sequence, use logfmt. If the structure is fixed but has no keys, use pattern. Anything else falls through to regexp. Before any parser runs, add a line filter, because parsers cost more than filtering and should only see lines that matter.

Parser choice follows the structure of each log line, after an early line filter.

How DeployOpen scopes and supports LogQL parser work

DeployOpen treats LogQL parser work as part of the wider Loki platform, starting from the log formats your services actually emit. We agree the scope in writing, build and test parser queries against your own log samples, and hand over documented patterns your team can maintain.

How we scope

  • Inventory the log formats each service emits and mark which ones are already json or logfmt
  • Record which fields dashboards and alerts need, so only those are extracted at query time
  • Agree in writing which unusual log lines need pattern or regexp and which can be left as raw text
  • Note the label sanitization rules that will apply to every extracted field name
  • Engagements are fixed-scope, with deliverables and timelines agreed before work starts

How we build

  • Write parser stages that filter with line filters before extracting fields, keeping queries cheap
  • Test each parser against representative sample lines, including malformed and edge-case entries
  • Compare query time over a short range and a long range to see how parser cost grows
  • Replace regexp stages with json or logfmt where the source format allows a structural change
  • Confirm the final field names after sanitization so dashboards reference the correct labels

How we hand over

  • Document each parser expression, the log format it targets and the fields it produces
  • Provide a library of tested example queries for Grafana Explore and dashboard panels
  • Record known limits, such as lines that do not match a pattern and how they appear in results
  • Walk your engineers through the parser set and the review steps for new log formats
  • Deliver the documentation and query library as part of the agreed scope

How we support

  • Review new services and log format changes against the documented parser conventions
  • Retest existing parser queries after Loki upgrades or changes to application log output
  • Ongoing support, upgrades and continuous testing are available as a retainer
  • Quotes follow from the written scope, so ask for the parser inventory to be listed explicitly
  • Confirm with your own environment which log volumes and time ranges your teams query most

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.