grafanago-templatesgrafana-loki

Custom legend in grafana panel using template expressions not working


I have a grafana v10.2.2 dashboard time series panel and I'm struggling to customize the legend on it.

According to the docs, I could use templates like the following to customize the values shown, but instead I'm getting the booth results.

Expression used:

{{ if eq "1" "2" }} true {{ else }} false {{ end }}

Results: Grafana dashboard label

My practical use case is to show a label value app if it is defined or the fixed value "Unknown" when it's absent.

I tried it with if and unless blocks, but none of the functions seemed to work, the function blocks are being ignored.

Thanks for any thoughts shared on it.


Solution

  • Let's try to implement real case: My practical use case is to show a label value app if it is defined or the fixed value "Unknown" when it's absent.

    Let's transform it to: app label should have original app label value or if app label doesn't exist then app label should have value Unknown.

    See linked doc:

    The text template format used in | line_format and | label_format support the usage of functions.

    So this is not Grafana feature (not Grafana's time series Legend field, which looks like you have used), but Loki query feature and it must be applied in the LogQL query.

    For example:

    {
      selector=~".+"
    }
    | json
    | label_format app="{{ if .app }}{{ .app }}{{ else }}Unknown{{ end }}"
    

    Example query may need some tweak (if there is any syntax issue, ...)

    Of course real query depends on format of your real logs. Just see example how mentioned template can be used in label_format. Just use then that app label in Grafana's time series Legend field (as {{app}}).