Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow custom Registry on HttpMetricsLayerBuilder #139

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ pub struct HttpMetricsLayerBuilder {
skipper: PathSkipper,
is_tls: bool,
exporter: Option<String>,
registry: Option<Registry>,
}

impl Default for HttpMetricsLayerBuilder {
Expand All @@ -257,6 +258,7 @@ impl Default for HttpMetricsLayerBuilder {
skipper: PathSkipper::default(),
is_tls: false,
exporter: Some("prometheus".to_string()),
registry: None,
}
}
}
Expand Down Expand Up @@ -301,6 +303,11 @@ impl HttpMetricsLayerBuilder {
self
}

pub fn with_registry(mut self, registry: Registry) -> Self {
self.registry = Some(registry);
self
}

pub fn build(self) -> HttpMetricsLayer {
let mut resource = vec![];

Expand Down Expand Up @@ -426,7 +433,9 @@ impl HttpMetricsLayerBuilder {
}

fn build_prometheus(&self) -> (Registry, impl opentelemetry_sdk::metrics::reader::MetricReader) {
let registry = if let Some(prefix) = self.prefix.clone() {
let registry = if let Some(registry) = self.registry.clone() {
registry
} else if let Some(prefix) = self.prefix.clone() {
Registry::new_custom(Some(prefix), self.labels.clone()).expect("create prometheus registry")
} else {
Registry::new()
Expand Down Expand Up @@ -757,4 +766,24 @@ mod tests {
"<h1>Hello, World!</h1>"
}
}

#[test]
fn test_builder_with_custom_registry() {
let metrics = HttpMetricsLayerBuilder::new()
.with_registry(prometheus::default_registry().to_owned())
.build();

let _app = Router::new()
// export metrics at `/metrics` endpoint
.merge(metrics.routes::<()>())
.route("/", get(handler))
.route("/hello", get(handler))
.route("/world", get(handler))
// add the metrics middleware
.layer(metrics);

async fn handler() -> &'static str {
"<h1>Hello, World!</h1>"
}
}
}