1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use libopentelemetry::{sdk::Resource, KeyValue};
use libprometheus::{Encoder, TextEncoder};
use crate::{
http::{Method, StatusCode},
Endpoint, IntoEndpoint, Request, Response,
};
#[cfg_attr(docsrs, doc(cfg(feature = "prometheus")))]
#[derive(Default)]
pub struct PrometheusExporter {
global_labels: Vec<KeyValue>,
}
impl PrometheusExporter {
pub fn new() -> Self {
Default::default()
}
pub fn label(mut self, kv: KeyValue) -> Self {
self.global_labels.push(kv);
self
}
}
impl IntoEndpoint for PrometheusExporter {
type Endpoint = PrometheusExporterEndpoint;
fn into_endpoint(self) -> Self::Endpoint {
PrometheusExporterEndpoint {
exporter: opentelemetry_prometheus::exporter()
.with_resource(Resource::new(self.global_labels))
.init(),
}
}
}
#[doc(hidden)]
pub struct PrometheusExporterEndpoint {
exporter: opentelemetry_prometheus::PrometheusExporter,
}
#[async_trait::async_trait]
impl Endpoint for PrometheusExporterEndpoint {
type Output = Response;
async fn call(&self, req: Request) -> Self::Output {
if req.method() != Method::GET {
return StatusCode::METHOD_NOT_ALLOWED.into();
}
let encoder = TextEncoder::new();
let metric_families = self.exporter.registry().gather();
let mut result = Vec::new();
match encoder.encode(&metric_families, &mut result) {
Ok(()) => Response::builder().content_type("text/plain").body(result),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into(),
}
}
}