Skip to content

Commit b821f88

Browse files
ranger-rosstobz
andauthored
fix: Fixed Prometheus export unit formatting (#582)
This commit fixes improperly formatted metrics when `PrometheusBuilder::new().set_enable_unit_suffix(true)` is enabled. Previously histogram metrics would have been formatted as: * `<name>-sum-<unit>` * `<name>-count-<unit>` * `<name>-bucket-<unit>` However the correct formatting is: * `<name>-<unit>-sum` * `<name>-<unit>-count` * `<name>-<unit>-bucket` Co-authored-by: Toby Lawrence <tobz@users.noreply.github.com>
1 parent 729f6e1 commit b821f88

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

metrics-exporter-prometheus/src/formatting.rs

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,8 @@ pub fn write_metric_line<T, T2>(
7777

7878
match unit {
7979
Some(Unit::Count) | None => {}
80-
Some(Unit::Percent) => {
81-
buffer.push('_');
82-
buffer.push_str("ratio");
83-
}
84-
Some(unit) => {
85-
buffer.push('_');
86-
buffer.push_str(unit.as_str());
87-
}
80+
Some(Unit::Percent) => add_unit(buffer, "ratio"),
81+
Some(unit) => add_unit(buffer, unit.as_str()),
8882
}
8983

9084
if !labels.is_empty() || additional_label.is_some() {
@@ -118,6 +112,29 @@ pub fn write_metric_line<T, T2>(
118112
buffer.push('\n');
119113
}
120114

115+
fn add_unit(buffer: &mut String, unit: &str) {
116+
const SUM_SUFFIX: &str = "_sum";
117+
const COUNT_SUFFIX: &str = "_count";
118+
const BUCKET_SUFFIX: &str = "_bucket";
119+
120+
if buffer.ends_with(SUM_SUFFIX) {
121+
let suffix_pos = buffer.len() - SUM_SUFFIX.len();
122+
buffer.insert(suffix_pos, '_');
123+
buffer.insert_str(suffix_pos + 1, unit);
124+
} else if buffer.ends_with(COUNT_SUFFIX) {
125+
let suffix_pos = buffer.len() - COUNT_SUFFIX.len();
126+
buffer.insert(suffix_pos, '_');
127+
buffer.insert_str(suffix_pos + 1, unit);
128+
} else if buffer.ends_with(BUCKET_SUFFIX) {
129+
let suffix_pos = buffer.len() - BUCKET_SUFFIX.len();
130+
buffer.insert(suffix_pos, '_');
131+
buffer.insert_str(suffix_pos + 1, unit);
132+
} else {
133+
buffer.push('_');
134+
buffer.push_str(unit);
135+
}
136+
}
137+
121138
/// Sanitizes a metric name to be valid under the Prometheus [data model].
122139
///
123140
/// [data model]: https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels

0 commit comments

Comments
 (0)