const HTTP_REQUESTS_TOTAL: &str = "http_requests_total";
const HTTP_REQUEST_DURATION_SECONDS: &str = "http_request_duration_seconds";
pub fn record_http_request(method: &str, path: &str, status: u16, latency: std::time::Duration) {
let method = method.to_owned();
let path = path.to_owned();
let status = status.to_string();
metrics::counter!(
HTTP_REQUESTS_TOTAL,
"method" => method.clone(),
"path" => path.clone(),
"status" => status.clone(),
)
.increment(1);
metrics::histogram!(
HTTP_REQUEST_DURATION_SECONDS,
"method" => method,
"path" => path,
"status" => status,
)
.record(latency.as_secs_f64());
}
pub fn inc_counter(name: &'static str, value: u64, labels: &[(&'static str, &str)]) {
let labels: Vec<metrics::Label> =
labels.iter().map(|(k, v)| metrics::Label::new(*k, v.to_string())).collect();
metrics::counter!(name, labels).increment(value);
}
pub fn observe(name: &'static str, value: f64, labels: &[(&'static str, &str)]) {
let labels: Vec<metrics::Label> =
labels.iter().map(|(k, v)| metrics::Label::new(*k, v.to_string())).collect();
metrics::histogram!(name, labels).record(value);
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn record_http_request_does_not_panic_without_recorder() {
record_http_request("GET", "/users/{id}", 200, Duration::from_millis(7));
record_http_request("POST", "/login", 401, Duration::from_micros(250));
}
#[test]
fn thin_wrappers_do_not_panic_without_recorder() {
inc_counter("test_counter_total", 3, &[("label", "value")]);
observe("test_histogram", 1.5, &[]);
}
}