Loki Query for Counting Logs by Status Code

Hi everyone,

I’m having trouble writing a Loki query in Grafana that returns the total number of logs for each status code (e.g., how many 200 status logs, how many 304 status logs, etc.). I’ve tried several queries, but most of them don’t compile correctly.

Here’s an example of what I’ve tried:

sum by (status) (count_over_time({job="nginx"}[1h]))

I’m using Loki as my data source and need to group the logs by the status label. Can anyone help me figure out what’s wrong with my query or suggest a better approach?

Thanks in advance for your help!

Please provide a sample of your logs.

172.20.0.1 - - [14/Dec/2024:16:39:35 +0000] “GET / HTTP/1.1” 304 0 “-” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36” “-”

Try this:

sum by (status) (
  count_over_time(
    {job="nginx"} | pattern `<ip> <_> <_> [<time>] "<method> <path> <protocol>" <status> <_> "<_>" "<_>" "<_>"`
    [1h]
  )
)

simulator: Simple LogQL simulator | Grafana Loki documentation

2 Likes

To count logs by status code in Loki, you can use the following Loki query:

logql

Copy code

{job="your_job_name"} | json | status_code=~"200|400|500" | count_over_time(status_code[1h])

Explanation:

  • Replace your_job_name with the actual job name or log label.
  • The | json parser extracts JSON fields from the log.
  • The status_code=~"200|400|500" filters the logs by status codes of interest (200, 400, and 500 in this example).
  • The count_over_time function counts the number of log entries within a specified time range (1 hour in this case).

Adjust the query for your specific use case and time range as needed.

To count logs by status code in Loki, filter logs by the status code (e.g., 200, 404) and apply a time-based aggregation function to count occurrences over a period. Adjust the status code and time range as necessary. For more detailed instructions, visit HostingMella.

Can someone help me with this?
https://community.grafana.com/t/auto-refresh-issue-with-grafana-promtail-and-loki-setup/138479

‫בתאריך יום ד׳, 25 בדצמ׳ 2024 ב-9:21 מאת ‪HostingMella via Grafana Labs Community Forums‬‏ <‪notifications@grafana.discoursemail.com‬‏>:‬