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

1 Like