But when there is no 200|400|401|403|429|404 of /api/a the return of sum(count_over_time({app="xxx"}|="{"|json|route="POST /api/a" , status=~200|400|401|403|429|404 [1m])) is no data ,and i wanna turn it to zero. So the total result can be 0%
It’d be really helpful to get an answer on this. Now that we can alert based on Loki LogQL metric queries, sending alerts based on error logs seems like a common use case. But if your query returns no data when there are no error logs, it’s impossible to get your alert to work properly.
Came up with kinda ugly solution. Basic idea is that you should negate your regexp first, and than subtract this value from sum without conditions. Something like this:
sum(x) - sum ( x | code !~"^5…")
I agree that this is a useful feature.
For example if I display graph line of number of errors in logs - if there are none I want it to be displayed as 0 and that it won’t disappear from the graph.
To handle cases in LogQL where a query returns null or “no data” and convert it to zero, you can use the or operator along with a conditional expression. Here’s how you can modify your query to achieve that:
Modified Query
logql
sum(count_over_time({app=“xxx”}|=“{”|json|route=“POST /api/a”, status=~“200|400|401|403|429|404”[1m])) or 0
Complete Percent Calculation
To ensure the entire percentage calculation correctly handles cases where the numerator might be zero (resulting in "no data"), you can wrap your entire division in an `or` statement:
logql
(sum(count_over_time({app="xxx"}|="{"|json|route="POST /api/a", status=~"200|400|401|403|429|404"[1m])) or 0) /
(sum(count_over_time({app="xxx"}|="{"|json|route="POST /api/a"[1m])) or 1) * 100
1. **Handling No Data:** The `or 0` part ensures that if the `sum(count_over_time(...))` returns `no data`, it will instead return `0`.
2. **Preventing Division by Zero:** The second part of the division uses `or 1`. This means that if there are no requests at all (the denominator is `0`), it will default to `1` instead. This prevents division by zero, and if the numerator is also `0`, the entire expression will yield `0%`.
3. **Calculating Percentage:** Finally, multiplying by `100` at the end gives you the percentage value.