Jerald Baker
Jerald Baker

Reputation: 1359

PromQL - Rename Output metrics label

If I query something like this :-

requests_total{app='myApp', status='200'}

I get

requests_total{app='myApp', status='200', uri='/blahblah', otherLabels='othervalues'}  50

In the output, is it possible to rename labels, for example: "app" to "service", "status" to "responseCode" ?

I have no control over input metrics, but there is another system which expects metrics to follow a specific naming convention.

Upvotes: 1

Views: 2535

Answers (1)

valyala
valyala

Reputation: 17860

It is possible to rename labels with label_replace function. For example, the following query adds service label with the value of the original app label:

label_replace(
  requests_total{app='myApp', status='200'},
  "service",
  "$1",
  "app",
  "(.+)"
)

Note that the query doesn't remove the original app label from matching time series. If you need removing the original app label, then use the following query:

label_replace(
  label_replace(
    requests_total{app='myApp', status='200'},
    "service",
    "$1",
    "app",
    "(.+)"
  ),
  "app",
  "",
  "app",
  "(.+)"
)

The outer label_replace() substitutes the app label with an empty value, so the label is removed from the resulting time series.

If you need subsituting multiple labels, then you need to write multiple nested label_replace() function calls. For example, the following query copies app label into service and status label into responseCode:

label_replace(
  label_replace(
    requests_total{app='myApp', status='200'},
    "service",
    "$1",
    "app",
    "(.+)"
  ),
  "responseCode",
  "$1",
  "status",
  "(.+)"
)

P.S. There is an alternative Prometheus-like solution I work on, which provides easier to use function for this particular case. The solution is named VictoriaMetrics. It provides label_move function for exactly this case. For example, the following MetricsQL query renames app into service and status into responseCode:

label_move(
  requests_total{app='myApp', status='200'},
  "app", "service",
  "status", "responseCode",
)

Upvotes: 2

Related Questions