From a9d933c2a49d079da77d1b2551f7b4d432f30a93 Mon Sep 17 00:00:00 2001 From: Punya Biswal Date: Fri, 22 Sep 2023 14:40:31 -0400 Subject: [PATCH] [exporters/prometheus] Omit underscore suffix for unitless metrics Fixes #2317 --- exporters/prometheus/src/exporter_utils.cc | 5 ++++- exporters/prometheus/test/exporter_utils_test.cc | 9 +++++++++ exporters/prometheus/test/prometheus_test_helper.h | 4 ++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/exporters/prometheus/src/exporter_utils.cc b/exporters/prometheus/src/exporter_utils.cc index 966d665df6..95ff12a49a 100644 --- a/exporters/prometheus/src/exporter_utils.cc +++ b/exporters/prometheus/src/exporter_utils.cc @@ -42,7 +42,10 @@ std::vector PrometheusExporterUtils::TranslateT auto unit = metric_data.instrument_descriptor.unit_; auto sanitized = SanitizeNames(origin_name); prometheus_client::MetricFamily metric_family; - metric_family.name = sanitized + "_" + unit; + metric_family.name = sanitized; + if (!unit.empty()) { + metric_family.name += "_" + unit; + }; metric_family.help = metric_data.instrument_descriptor.description_; auto time = metric_data.end_ts.time_since_epoch(); for (const auto &point_data_attr : metric_data.point_data_attr_) diff --git a/exporters/prometheus/test/exporter_utils_test.cc b/exporters/prometheus/test/exporter_utils_test.cc index 2222787787..8de172181a 100644 --- a/exporters/prometheus/test/exporter_utils_test.cc +++ b/exporters/prometheus/test/exporter_utils_test.cc @@ -157,4 +157,13 @@ TEST(PrometheusExporterUtils, SanitizeName) ASSERT_EQ(exporter::metrics::SanitizeNameTester::sanitize("name?__name:"), "name_name:"); } +TEST(PrometheusExporterUtils, HandleMissingUnit) +{ + TestDataPoints dp; + metric_sdk::ResourceMetrics data = dp.CreateSumPointData(""); + std::vector family = + PrometheusExporterUtils::TranslateToPrometheus(data); + ASSERT_EQ(family.begin()->name, "library_name"); +} + OPENTELEMETRY_END_NAMESPACE diff --git a/exporters/prometheus/test/prometheus_test_helper.h b/exporters/prometheus/test/prometheus_test_helper.h index d42f66c6eb..34ccfe8bcd 100644 --- a/exporters/prometheus/test/prometheus_test_helper.h +++ b/exporters/prometheus/test/prometheus_test_helper.h @@ -25,7 +25,7 @@ struct TestDataPoints /** * Helper function to create ResourceMetrics */ - inline metric_sdk::ResourceMetrics CreateSumPointData() + inline metric_sdk::ResourceMetrics CreateSumPointData(std::string unit = "unit") { metric_sdk::SumPointData sum_point_data{}; sum_point_data.value_ = 10.0; @@ -34,7 +34,7 @@ struct TestDataPoints metric_sdk::ResourceMetrics data; data.resource_ = &resource; metric_sdk::MetricData metric_data{ - metric_sdk::InstrumentDescriptor{"library_name", "description", "unit", + metric_sdk::InstrumentDescriptor{"library_name", "description", unit, metric_sdk::InstrumentType::kCounter, metric_sdk::InstrumentValueType::kDouble}, metric_sdk::AggregationTemporality::kDelta, opentelemetry::common::SystemTimestamp{},