Skip to content

Commit

Permalink
Add formatMetricName to ensure it is a valid Prometheus metric name (#19
Browse files Browse the repository at this point in the history
)
  • Loading branch information
lucaslopezf authored Oct 25, 2023
1 parent cad41f0 commit 1b3ab47
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pkg/metrics/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/zondax/golem/pkg/metrics/collectors"
"regexp"
"strings"
)

type collectorRegister func(name, help string, labels []string, handler MetricHandler) (prometheus.Collector, error)
Expand All @@ -19,6 +21,7 @@ var (
func (t *taskMetrics) RegisterMetric(name string, help string, labels []string, handler MetricHandler) error {
var metric prometheus.Collector

name = formatMetricName(name)
registerFn, ok := collectorRegisterMap[handler.Type()]
if !ok {
return fmt.Errorf("unsupported metric type")
Expand Down Expand Up @@ -74,3 +77,12 @@ func registerGauge(name, help string, labels []string, handler MetricHandler) (p

return prometheus.NewGaugeVec(prometheus.GaugeOpts{Name: name, Help: help}, labels), nil
}

// FormatMetricName formats the given string to make it a valid Prometheus metric name.
func formatMetricName(name string) string {
name = strings.ReplaceAll(name, "-", "_")
re := regexp.MustCompile("[^a-zA-Z0-9_]+")
name = re.ReplaceAllString(name, "_")

return name
}
20 changes: 20 additions & 0 deletions pkg/metrics/register_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,23 @@ func TestRegisterMetric(t *testing.T) {
assert.IsType(t, MetricDetail{}, tm.metrics["test_counter"])
assert.IsType(t, prometheus.NewCounter(prometheus.CounterOpts{}), tm.metrics["test_counter"].Collector)
}

func TestFormatMetricName(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"router-name", "router_name"},
{"router name", "router_name"},
{"router$name", "router_name"},
{"routerName", "routerName"},
{"router@name-123", "router_name_123"},
}

for _, test := range tests {
t.Run(test.input, func(t *testing.T) {
result := formatMetricName(test.input)
assert.Equal(t, test.expected, result)
})
}
}

0 comments on commit 1b3ab47

Please sign in to comment.