modi/mw/
metrics.rs

1use std::time::Instant;
2
3use crate::otel::otel_metrics::{Counter, Histogram};
4use crate::otel::semantic_conventions::trace;
5use crate::otel::*;
6use crate::prelude::*;
7use crate::salvo::http::ResBody;
8
9/// Middleware for metrics with OpenTelemetry.
10pub struct Metrics {
11    request_count: Counter<u64>,
12    error_count: Counter<u64>,
13    duration: Histogram<f64>,
14}
15
16impl Metrics {
17    /// Create `Metrics` middleware with `meter`.
18    pub fn new(service_name: String) -> Self {
19        let meter = meter(service_name.clone());
20        Self {
21            request_count: meter
22                .u64_counter(service_name.clone() + "_request_count")
23                .with_description("total request count (since start of service)")
24                .init(),
25            error_count: meter
26                .u64_counter(service_name.clone() + "_error_count")
27                .with_description("failed request count (since start of service)")
28                .init(),
29            duration: meter
30                .f64_histogram(service_name.clone() + "_request_duration_ms")
31                .with_unit("milliseconds")
32                .with_description(
33                    "request duration histogram (in milliseconds, since start of service)",
34                )
35                .init(),
36        }
37    }
38}
39
40#[async_trait]
41impl Handler for Metrics {
42    async fn handle(
43        &self,
44        req: &mut Request,
45        depot: &mut Depot,
46        res: &mut Response,
47        ctrl: &mut FlowCtrl,
48    ) {
49        let mut labels = Vec::with_capacity(3);
50        labels.push(KeyValue::new(
51            trace::HTTP_REQUEST_METHOD,
52            req.method().to_string(),
53        ));
54        labels.push(KeyValue::new(trace::URL_FULL, req.uri().to_string()));
55
56        let s = Instant::now();
57        ctrl.call_next(req, depot, res).await;
58        let elapsed = s.elapsed();
59
60        let status = res.status_code.unwrap_or(StatusCode::OK);
61        labels.push(KeyValue::new(
62            trace::HTTP_RESPONSE_STATUS_CODE,
63            status.as_u16() as i64,
64        ));
65        if status.is_client_error() || status.is_server_error() {
66            self.error_count.add(1, &labels);
67            let msg = if let ResBody::Error(body) = &res.body {
68                body.to_string()
69            } else {
70                format!("ErrorCode: {}", status.as_u16())
71            };
72            labels.push(KeyValue::new(trace::EXCEPTION_MESSAGE, msg));
73        }
74
75        self.request_count.add(1, &labels);
76        self.duration
77            .record(elapsed.as_secs_f64() * 1000.0, &labels);
78    }
79}