'Escape special characters in Prometheus metric names?

When exposing Prometheus metrics from a legacy application, I find that some metrics contain invalid characters such as my.metric, my-metric, my:metric

Instead of changing the metric names in my legacy app (it's massive) I could for instance escape these characters: my.metric, my-metric, my:metric

Or, I could surround these names in (single or double) quotes: "my.metric", "my-metric", "my:metric" 'my.metric', 'my-metric', 'my:metric'

Would these play well with existing Prometheus functionality? Would it be ok to upstream/implement support for any or both of these?



Solution 1:[1]

Quotes aren't valid characters for Prometheus metric names either.

The standard way to handle this is to convert the invalid characters to underscores: https://prometheus.io/docs/instrumenting/writing_exporters/#naming

Solution 2:[2]

Prometheus allows only the pre-defined set of chars in metric names, which match the following regexp: [a-zA-Z0-9:_]. Other Prometheus-like systems such as VictoriaMetrics allow other chars in metric names. In this case the following options exist for escaping special chars in queries:

  • to use the filter on __name__ pseudo-label according to time series selectors docs. For example, {__name__="metric-name.with special{chars"} would select time series with metric-name.with special{chars names
  • to prepend special chars in metric names with backslashes. For example, metric\-name\.with\ special\{chars

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 brian-brazil
Solution 2 valyala