Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 563 of 8028. Security and ObservabilityFree lesson

Querying Logs with LogQL Syntax

Learners will master LogQL to perform advanced filtering, range vector aggregation, and log-to-metric transformations directly within the Grafana interface.

In this lesson, you will master the LogQL syntax to perform advanced filtering, range vector aggregation, and log-to-metric transformations directly within Grafana.

While Prometheus metrics track what is happening in your cluster, Grafana Loki’s LogQL allows you to inspect the why by querying the raw log streams generated by your containers. LogQL is intentionally similar to PromQL, making it intuitive for those already comfortable with metrics.

Filtering and Stream Selectors

Every query begins with a log stream selector to narrow down your search using labels. To find logs from a specific namespace and pod, use: {namespace="production", pod=~"auth-service-.*"} You can refine this further with filter expressions (the |= operator acts like grep): {job="varlogs"} |= "error" != "timeout" This query isolates logs from varlogs containing "error" but excluding those mentioning "timeout".

Aggregation and Log-to-Metric Transformations

LogQL shines when you need to turn unstructured logs into quantitative data. If your logs are structured (e.g., JSON), you can use the json parser to extract fields and perform calculations.

Suppose your logs contain a duration field. You can convert these log lines into a time-series graph by calculating the rate of occurrences:

sum by (status) (
  rate({job="api-gateway"} | json | duration > 500ms [5m])
)

In this example, the query parses JSON-formatted logs, filters for any request with a duration greater than 500ms, and aggregates the rate of these slow requests over a 5-minute window, grouped by the status label.

Why this matters

By performing these transformations directly in the Explore tab of Grafana, you eliminate the need to ship logs to an external database just to count errors or calculate latency. You gain immediate visibility into application behavior without leaving your existing dashboard environment.

Key Takeaway: LogQL allows you to treat log streams as both text-based diagnostic tools and as a dynamic data source for generating real-time operational metrics.