Handling 'no data' in Grafana subtraction query using LogQL with Loki

 In Grafana with Loki, you can handle 'no data' cases when performing subtraction queries using LogQL. Subtraction queries allow you to calculate the difference between two metrics or log stream counts. When dealing with 'no data' scenarios, you might want to set a default value or display a meaningful result. Here's how you can approach it:


Suppose you have two LogQL queries: `queryA` and `queryB`. To handle 'no data' situations, you can use the `if` function to check if one or both of these queries result in 'no data' and assign a default value in such cases. Here's a general template:


```LogQL

if(

  <condition_for_no_data>,

  <default_value>,

  <subtraction_query>

)

```


For example, if you want to subtract `queryA` from `queryB` and display '0' when there's 'no data' in either query, you can use the following expression:


```LogQL

if(

  (count_over_time(queryA[5m]) == 0) or (count_over_time(queryB[5m]) == 0),

  0,

  count_over_time(queryB[5m]) - count_over_time(queryA[5m])

)

```


In this example:


- `count_over_time(queryA[5m])` and `count_over_time(queryB[5m])` count the number of log entries returned by `queryA` and `queryB` within the last 5 minutes, respectively.


- The `if` function checks if either of these counts is zero, indicating 'no data' in either query.


- If 'no data' is detected in either query, it returns '0' as the default value.


- If both queries have data, it performs the subtraction and returns the result.


You can adjust the time range `[5m]` to match your specific requirements, and replace `0` with any other default value you want to use.


By using the `if` function in this way, you can gracefully handle 'no data' scenarios when performing subtraction queries in Grafana with Loki.

Comments

Popular posts from this blog

bad character U+002D '-' in my helm template

GitLab pipeline stopped working with invalid yaml error

How do I add a printer in OpenSUSE which is being shared by a CUPS print server?