Search code examples
grafanagrafana-lokigrafana-variable

Grafana Loki - Simple Boolean Logic in Queries with Variables


I have what should be a straightforward request, but I have looked around a bit and have not seen an example of how to accomplish this. Basically, I have a couple of dashboard variables so that users can filter log results. The Log Search textbox variable filters the logs by text entered and the Search Field dropdown variable defaults to “All Fields”. Users can update that to search for text in a specific field.

I have a panel to display the Log File Search Results and the Grafana Loki Query in the panel to execute the filtering. I have everything working except for the default “All Fields” situation. I’m already filtering all of the logs based on the text entered. Then when I get to the specific field filtering I want to skip that extra filter if “All Fields is selected”. So I just want to do a simple conditional expression, something like ${searchField:value} == ‘All’ or [field filter].

This seems like basic functionality, but doesn’t seem available? So hopefully I’m just missing something. I broke out the single query into two separate ones, searchAllFields and searchIndividualFields, and was thinking I could use one or the other in the transform based on the Search Field variable selection. Still unclear how to accomplish that in the transform.

I feel like this is something that must come up again and again, querying against an entire datasource or just a single field in that datasource. How are people accomplishing this?

enter image description here

Dashboard variables for textBoxSearchValue and searchField:

enter image description here


Solution

  • Loki doesn't allow comparison of two arbitrary strings in it's label filtering expressions. The only way to introduce something like you want I can imagine is to work with some labels, perhaps non existing ones.

    You can add or ${searchField:value} = "" to your query (to the last part). Assuming your items don't have a All label (if does - change value of All fields to something that doesn't exist), this will result in filtering either by required field or by non-existing field being equal to empty string (which is always true).

    This solution is not ideal: if some of your labels can be empty, and you'll try to apply filtering over them, empty ones will be returned together with those containing search term. At the moment, I don't think this problem can be solved.