Skip to content

Commit 0c8a2c5

Browse files
committed
add TestSanitizePrometheusName
1 parent da04b2f commit 0c8a2c5

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

util/metrics/metrics_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,27 @@ func TestSanitizeTelemetryName(t *testing.T) {
112112
})
113113
}
114114
}
115+
116+
func TestSanitizePrometheusName(t *testing.T) {
117+
for _, tc := range []struct{ in, out string }{
118+
{in: "algod_counter_x", out: "algod_counter_x"},
119+
{in: "algod_counter_x{a=b}", out: "algod_counter_x_a_b_"},
120+
{in: "this_is1-a-name0", out: "this_is1_a_name0"},
121+
{in: "myMetricName1:a=yes", out: "myMetricName1_a_yes"},
122+
{in: "myMetricName1:a=yes,b=no", out: "myMetricName1_a_yes_b_no"},
123+
{in: "0myMetricName1", out: "_myMetricName1"},
124+
{in: "myMetricName1{hello=x}", out: "myMetricName1_hello_x_"},
125+
{in: "myMetricName1.moreNames-n.3", out: "myMetricName1_moreNames_n_3"},
126+
{in: "-my-metric-name", out: "_my_metric_name"},
127+
{in: `label-counter:label="a label value"`, out: "label_counter_label__a_label_value_"},
128+
{in: "go/gc/cycles/total:gc-cycles", out: "go_gc_cycles_total_gc_cycles"},
129+
{in: "go/gc/heap/allocs:bytes", out: "go_gc_heap_allocs_bytes"},
130+
{in: "go/gc/heap/allocs:objects", out: "go_gc_heap_allocs_objects"},
131+
{in: "go/memory/classes/os-stacks:bytes", out: "go_memory_classes_os_stacks_bytes"},
132+
{in: "go/memory/classes/heap/free:bytes", out: "go_memory_classes_heap_free_bytes"},
133+
} {
134+
t.Run(tc.in, func(t *testing.T) {
135+
require.Equal(t, tc.out, sanitizePrometheusName(tc.in))
136+
})
137+
}
138+
}

util/metrics/registryCommon.go

+1-3
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,8 @@ func sanitizeTelemetryName(name string) string {
4343
return sanitizeTelemetryCharactersRegexp.ReplaceAllString(name, "_")
4444
}
4545

46-
var sanitizePrometheusCharactersRegexp = regexp.MustCompile("(^[^a-zA-Z_]|[^a-zA-Z0-9_])")
47-
4846
// sanitizePrometheusName ensures a metric name reported to telemetry doesn't contain any
4947
// non-alphanumeric characters (apart from _) and doesn't start with a number.
5048
func sanitizePrometheusName(name string) string {
51-
return sanitizePrometheusCharactersRegexp.ReplaceAllString(name, "_")
49+
return strings.ReplaceAll(sanitizeTelemetryName(name), "-", "_")
5250
}

0 commit comments

Comments
 (0)