io.opentelemetry.contrib.metrics.prometheus.clientbridge.NameSanitizer Maven / Gradle / Ivy
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.contrib.metrics.prometheus.clientbridge;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.regex.Pattern;
/** Sanitizes a metric or label name. */
class NameSanitizer implements Function {
private static final Pattern SANITIZE_PREFIX_PATTERN = Pattern.compile("^[^a-zA-Z_:]");
private static final Pattern SANITIZE_BODY_PATTERN = Pattern.compile("[^a-zA-Z0-9_:]");
private final Function delegate;
private final Map cache = new ConcurrentHashMap<>();
NameSanitizer() {
this(NameSanitizer::sanitizeMetricName);
}
// visible for testing
NameSanitizer(Function delegate) {
this.delegate = delegate;
}
@Override
public String apply(String labelName) {
return cache.computeIfAbsent(labelName, delegate);
}
private static String sanitizeMetricName(String metricName) {
return SANITIZE_BODY_PATTERN
.matcher(SANITIZE_PREFIX_PATTERN.matcher(metricName).replaceFirst("_"))
.replaceAll("_");
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy