use std::fmt::{Display, Write};
use crate::features::metrics::types::{DURATION_BUCKETS_SECONDS, DurationSummary};
pub(super) fn label_value(value: &str) -> String {
value
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
}
pub(super) fn write_help_and_type(body: &mut String, name: &str, help: &str, metric_type: &str) {
let _ = writeln!(body, "# HELP {name} {help}");
let _ = writeln!(body, "# TYPE {name} {metric_type}");
}
pub(super) fn write_metric_value(body: &mut String, name: &str, value: impl Display) {
let _ = writeln!(body, "{name} {value}");
}
pub(super) fn write_metric_with_labels(
body: &mut String,
name: &str,
labels: &str,
value: impl Display,
) {
let _ = writeln!(body, "{name}{{{labels}}} {value}");
}
pub(super) fn write_histogram(
body: &mut String,
name: &str,
labels: &str,
summary: &DurationSummary,
) {
for (index, upper_bound) in DURATION_BUCKETS_SECONDS.iter().enumerate() {
write_metric_with_labels(
body,
&format!("{name}_bucket"),
&format!("{labels},le=\"{upper_bound}\""),
summary.buckets[index],
);
}
write_metric_with_labels(
body,
&format!("{name}_bucket"),
&format!("{labels},le=\"+Inf\""),
summary.count,
);
write_metric_with_labels(
body,
&format!("{name}_sum"),
labels,
format!("{:.6}", summary.sum_seconds),
);
write_metric_with_labels(body, &format!("{name}_count"), labels, summary.count);
}