Search code examples
prometheusgrafanametricsregexp-replace

How do I group and sum grafana metric values after i use regex to transfrom labelnames


In grafana I have used this query to sum and group a query by path:

sum by(path) (increase(http_request_duration_seconds_count{applikasjon="kundebetjening-web", path=~"/api-gateway/([^/]+)/.*",environment="prod"}[$__range]))

After this i used transform and regex functionality in grafana so I can transform the labels from long pathnames like /<apiname>/listusers/user/name to only get the first part of the pathname for example /<apiname>

enter image description here

The result looks like this image enter image description here

As you can see each label is actually a unique path, but because I use regex to shorten the path, I get multiple labelnames on the right side of the chart that have the same name.

How can I combine the labelnames that are the same and sum their value so that instead of getting multiple labelnames with kunde-logg, I only get one and the sum of the metric of all the labelnames that are the same

Ive tried looking in the transform functionality to see if there is a way to combine the labels with no luck


Solution

  • Aggregate data on Prometheus' side.

    You can replace path with its segment using label_replace.

    In result your query would look like this:

    sum by(path_segment) (
      increase(
        label_replace(
          http_request_duration_seconds_count{applikasjon="kundebetjening-web", path=~"/api-gateway/([^/]+)/.*",environment="prod"},
          "path_segment", "$1",
          "path","/api-gateway/([^/]+)/.*"
        ) [$__range : ]
      )
    )
    

    Also notice that here used subquery syntax instead of usual range selector. Difference in that [$__range] can be applied only to the vector selectors, while [$__range : ] is applicable to results of functions (like label_replace) too.