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

Add actix-web example #76

Merged
merged 2 commits into from Aug 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Added a `with_prefix` method to `Registry` to allow initializing a registry with a prefix. See [PR 70].
- Added `Debug` implementations on most public types that were missing them. See [PR 71].
- Added example for actix-web framework. See [PR 76].

### Removed
- Remove `Add` trait implementation for a private type which lead to compile time conflicts with existing `Add` implementations e.g. on `String`. See [PR 69].
Expand All @@ -20,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[PR 69]: https://github.com/prometheus/client_rust/pull/69
[PR 70]: https://github.com/prometheus/client_rust/pull/70
[PR 71]: https://github.com/prometheus/client_rust/pull/71
[PR 76]: https://github.com/prometheus/client_rust/pull/76

## [0.16.0]

Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Expand Up @@ -27,6 +27,7 @@ pyo3 = "0.16"
quickcheck = "1"
rand = "0.8.4"
tide = "0.16"
actix-web = "4"

[[bench]]
name = "family"
Expand Down
74 changes: 74 additions & 0 deletions examples/actix-web.rs
@@ -0,0 +1,74 @@
use std::sync::Mutex;

use actix_web::{web, App, HttpResponse, HttpServer, Responder, Result};
use prometheus_client::encoding::text::{encode, Encode};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::registry::Registry;

#[derive(Clone, Hash, PartialEq, Eq, Encode)]
pub enum Method {
Get,
Post,
}

#[derive(Clone, Hash, PartialEq, Eq, Encode)]
pub struct MethodLabels {
pub method: Method,
}

pub struct Metrics {
requests: Family<MethodLabels, Counter>,
}

impl Metrics {
pub fn inc_requests(&self, method: Method) {
self.requests.get_or_create(&MethodLabels { method }).inc();
}
}

pub struct AppState {
pub registry: Registry,
}

pub async fn metrics_handler(state: web::Data<Mutex<AppState>>) -> Result<HttpResponse> {
let state = state.lock().unwrap();
let mut buf = Vec::new();
encode(&mut buf, &state.registry)?;
let body = std::str::from_utf8(buf.as_slice()).unwrap().to_string();
Ok(HttpResponse::Ok()
.content_type("application/openmetrics-text; version=1.0.0; charset=utf-8")
.body(body))
}

pub async fn some_handler(metrics: web::Data<Metrics>) -> impl Responder {
metrics.inc_requests(Method::Get);
"okay".to_string()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
let metrics = web::Data::new(Metrics {
requests: Family::default(),
});
let mut state = AppState {
registry: Registry::default(),
};
state.registry.register(
"requests",
"Count of requests",
Box::new(metrics.requests.clone()),
);
let state = web::Data::new(Mutex::new(state));

HttpServer::new(move || {
App::new()
.app_data(metrics.clone())
.app_data(state.clone())
.service(web::resource("/metrics").route(web::get().to(metrics_handler)))
.service(web::resource("/handler").route(web::get().to(some_handler)))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}