HOW-TO customize Grafana legend/label

A question that I’ve seen asked many time on the web is people asking how to shorten their Grafana legend/label.

E.g. using hostname as a legend will usually return the full FQDN, which can be too long if you have many hosts and make a mess of your panel.

standard legend using FQDN

Lots of searching show people having similar questions and a number of request for enhancements. In my case, there is a simple solution that work. Here is how.

Use the function label_replace(). So

rate(nginx_http_requests_total{instance=~"$instance", host="$host"}[5m])

turn into

label_replace(rate(nginx_http_requests_total{instance=~"$instance", host="$host"}[5m]), "hname", "$1", "instance", "(.*).foo.bar.local")

 

And the legend format changed from

{{instance}}-{{status}}  to {{hname}}-{{status}}
Shorter legend