gbserver/gb-monitoring/src/metrics.rs

81 lines
2.2 KiB
Rust
Raw Normal View History

2024-12-23 00:20:59 -03:00
use prometheus::{IntCounter, IntGauge, Histogram, Registry};
2024-12-22 20:56:52 -03:00
pub struct Metrics {
2024-12-23 00:20:59 -03:00
registry: Registry,
message_counter: IntCounter,
active_connections: IntGauge,
message_processing_time: Histogram,
2024-12-22 20:56:52 -03:00
}
impl Metrics {
2024-12-23 00:20:59 -03:00
pub fn new() -> Self {
2024-12-22 20:56:52 -03:00
let registry = Registry::new();
2024-12-23 00:20:59 -03:00
let message_counter = IntCounter::new(
"message_total",
"Total number of messages processed"
).unwrap();
let active_connections = IntGauge::new(
"active_connections",
"Number of active connections"
).unwrap();
let message_processing_time = Histogram::with_opts(
prometheus::HistogramOpts::new(
"message_processing_seconds",
"Time spent processing messages"
).buckets(vec![0.01, 0.05, 0.1, 0.5, 1.0, 2.0, 5.0])
).unwrap();
registry.register(Box::new(message_counter.clone())).unwrap();
registry.register(Box::new(active_connections.clone())).unwrap();
registry.register(Box::new(message_processing_time.clone())).unwrap();
Self {
registry,
message_counter,
2024-12-22 20:56:52 -03:00
active_connections,
2024-12-23 00:20:59 -03:00
message_processing_time,
}
2024-12-22 20:56:52 -03:00
}
2024-12-23 00:20:59 -03:00
pub fn increment_message_count(&self) {
self.message_counter.inc();
2024-12-22 20:56:52 -03:00
}
2024-12-23 00:20:59 -03:00
pub fn observe_processing_time(&self, duration_seconds: f64) {
self.message_processing_time.observe(duration_seconds);
2024-12-22 20:56:52 -03:00
}
2024-12-23 00:20:59 -03:00
pub fn set_active_connections(&self, count: i64) {
self.active_connections.set(count);
2024-12-22 20:56:52 -03:00
}
2024-12-23 00:20:59 -03:00
pub fn registry(&self) -> &Registry {
&self.registry
2024-12-22 20:56:52 -03:00
}
}
#[cfg(test)]
mod tests {
use super::*;
2024-12-23 00:20:59 -03:00
2024-12-22 20:56:52 -03:00
#[test]
2024-12-23 00:20:59 -03:00
fn test_metrics() {
let metrics = Metrics::new();
2024-12-22 20:56:52 -03:00
2024-12-23 00:20:59 -03:00
metrics.increment_message_count();
assert_eq!(metrics.message_counter.get(), 1);
metrics.set_active_connections(10);
assert_eq!(metrics.active_connections.get(), 10);
metrics.observe_processing_time(0.5);
2024-12-22 20:56:52 -03:00
let mut buffer = Vec::new();
2024-12-23 00:20:59 -03:00
let encoder = prometheus::TextEncoder::new();
encoder.encode(&metrics.registry().gather(), &mut buffer).unwrap();
2024-12-22 20:56:52 -03:00
assert!(!buffer.is_empty());
}
}