diff --git a/pkg/metrics/register.go b/pkg/metrics/register.go index 149a67c..a8c582b 100644 --- a/pkg/metrics/register.go +++ b/pkg/metrics/register.go @@ -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) @@ -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") @@ -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 +} diff --git a/pkg/metrics/register_test.go b/pkg/metrics/register_test.go index 8f7f18a..cfa0c4c 100644 --- a/pkg/metrics/register_test.go +++ b/pkg/metrics/register_test.go @@ -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) + }) + } +}