Skip to content

Commit

Permalink
add TestSanitizePrometheusName
Browse files Browse the repository at this point in the history
  • Loading branch information
cce committed May 25, 2022
1 parent da04b2f commit 0c8a2c5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
24 changes: 24 additions & 0 deletions util/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,27 @@ func TestSanitizeTelemetryName(t *testing.T) {
})
}
}

func TestSanitizePrometheusName(t *testing.T) {
for _, tc := range []struct{ in, out string }{
{in: "algod_counter_x", out: "algod_counter_x"},
{in: "algod_counter_x{a=b}", out: "algod_counter_x_a_b_"},
{in: "this_is1-a-name0", out: "this_is1_a_name0"},
{in: "myMetricName1:a=yes", out: "myMetricName1_a_yes"},
{in: "myMetricName1:a=yes,b=no", out: "myMetricName1_a_yes_b_no"},
{in: "0myMetricName1", out: "_myMetricName1"},
{in: "myMetricName1{hello=x}", out: "myMetricName1_hello_x_"},
{in: "myMetricName1.moreNames-n.3", out: "myMetricName1_moreNames_n_3"},
{in: "-my-metric-name", out: "_my_metric_name"},
{in: `label-counter:label="a label value"`, out: "label_counter_label__a_label_value_"},
{in: "go/gc/cycles/total:gc-cycles", out: "go_gc_cycles_total_gc_cycles"},
{in: "go/gc/heap/allocs:bytes", out: "go_gc_heap_allocs_bytes"},
{in: "go/gc/heap/allocs:objects", out: "go_gc_heap_allocs_objects"},
{in: "go/memory/classes/os-stacks:bytes", out: "go_memory_classes_os_stacks_bytes"},
{in: "go/memory/classes/heap/free:bytes", out: "go_memory_classes_heap_free_bytes"},
} {
t.Run(tc.in, func(t *testing.T) {
require.Equal(t, tc.out, sanitizePrometheusName(tc.in))
})
}
}
4 changes: 1 addition & 3 deletions util/metrics/registryCommon.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,8 @@ func sanitizeTelemetryName(name string) string {
return sanitizeTelemetryCharactersRegexp.ReplaceAllString(name, "_")
}

var sanitizePrometheusCharactersRegexp = regexp.MustCompile("(^[^a-zA-Z_]|[^a-zA-Z0-9_])")

// sanitizePrometheusName ensures a metric name reported to telemetry doesn't contain any
// non-alphanumeric characters (apart from _) and doesn't start with a number.
func sanitizePrometheusName(name string) string {
return sanitizePrometheusCharactersRegexp.ReplaceAllString(name, "_")
return strings.ReplaceAll(sanitizeTelemetryName(name), "-", "_")
}

0 comments on commit 0c8a2c5

Please sign in to comment.