|
5 | 5 |
|
6 | 6 | package io.opentelemetry.exporter.prometheus; |
7 | 7 |
|
| 8 | +import static io.prometheus.metrics.model.snapshots.PrometheusNaming.prometheusName; |
8 | 9 | import static io.prometheus.metrics.model.snapshots.PrometheusNaming.sanitizeLabelName; |
9 | 10 | import static io.prometheus.metrics.model.snapshots.PrometheusNaming.sanitizeMetricName; |
10 | 11 | import static java.util.Objects.requireNonNull; |
@@ -474,7 +475,7 @@ private Labels convertAttributes( |
474 | 475 | attributes.forEach( |
475 | 476 | (key, value) -> |
476 | 477 | labelNameToValue.put( |
477 | | - sanitizeLabelName(key.getKey()), toLabelValue(key.getType(), value))); |
| 478 | + convertLabelName(key.getKey()), toLabelValue(key.getType(), value))); |
478 | 479 |
|
479 | 480 | for (int i = 0; i < additionalAttributes.length; i += 2) { |
480 | 481 | labelNameToValue.putIfAbsent( |
@@ -504,7 +505,7 @@ private Labels convertAttributes( |
504 | 505 | Object attributeValue = resourceAttributes.get(attributeKey); |
505 | 506 | if (attributeValue != null) { |
506 | 507 | labelNameToValue.putIfAbsent( |
507 | | - sanitizeLabelName(attributeKey.getKey()), attributeValue.toString()); |
| 508 | + convertLabelName(attributeKey.getKey()), attributeValue.toString()); |
508 | 509 | } |
509 | 510 | } |
510 | 511 | } |
@@ -544,14 +545,24 @@ private List<AttributeKey<?>> filterAllowedResourceAttributeKeys(@Nullable Resou |
544 | 545 | return allowedAttributeKeys; |
545 | 546 | } |
546 | 547 |
|
| 548 | + /** |
| 549 | + * Convert an attribute key to a legacy Prometheus label name. {@code prometheusName} converts |
| 550 | + * non-standard characters (dots, dashes, etc.) to underscores, and {@code sanitizeLabelName} |
| 551 | + * strips invalid leading prefixes. |
| 552 | + */ |
| 553 | + private static String convertLabelName(String key) { |
| 554 | + return sanitizeLabelName(prometheusName(key)); |
| 555 | + } |
| 556 | + |
547 | 557 | private static MetricMetadata convertMetadata(MetricData metricData) { |
548 | | - String name = sanitizeMetricName(metricData.getName()); |
| 558 | + String name = sanitizeMetricName(prometheusName(metricData.getName())); |
549 | 559 | String help = metricData.getDescription(); |
550 | 560 | Unit unit = PrometheusUnitsHelper.convertUnit(metricData.getUnit()); |
551 | 561 | if (unit != null && !name.endsWith(unit.toString())) { |
552 | 562 | name = name + "_" + unit; |
553 | 563 | } |
554 | | - // Repeated __ are not allowed according to spec, although this is allowed in prometheus |
| 564 | + // Repeated __ are discouraged according to spec, although this is allowed in prometheus, see |
| 565 | + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/compatibility/prometheus_and_openmetrics.md#metric-metadata-1 |
555 | 566 | while (name.contains("__")) { |
556 | 567 | name = name.replace("__", "_"); |
557 | 568 | } |
|
0 commit comments