Skip to content

Commit

Permalink
Add example demonstrating metrics usage (#203)
Browse files Browse the repository at this point in the history
  • Loading branch information
RAnders00 authored Nov 26, 2023
1 parent fe8b5fa commit b525dc8
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Version numbers follow [Semantic Versioning](https://semver.org/).
- Minor: Added support for reply-parent tags (#189)
- Minor: Tokens in `CredentialsPair` and `UserAccessToken` are now redacted in their `Debug` output. Same
applies to the `client_secret` in `RefreshingLoginCredentials`. (#199)
- Minor: Added example demonstrating usage of `metrics-collection` feature. (#203)

## v5.0.1

Expand Down
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ maplit = "1"
serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread"] }
tracing-subscriber = "0.3"
# For the metrics example
axum = "0.6"

[lib]
name = "twitch_irc"
Expand All @@ -61,6 +63,10 @@ path = "src/lib.rs"
name = "simple_listener"
required-features = ["transport-tcp", "transport-tcp-native-tls"]

[[example]]
name = "metrics"
required-features = ["transport-tcp", "transport-tcp-native-tls", "metrics-collection"]

[features]
# If you add a feature here don't forget to add it to the test workflow in workflows/rust.yml!
default = ["transport-tcp", "transport-tcp-native-tls"]
Expand Down
66 changes: 66 additions & 0 deletions examples/metrics.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use std::collections::HashMap;

use axum::routing::get;
use axum::Router;
use prometheus::TextEncoder;
use twitch_irc::login::StaticLoginCredentials;
use twitch_irc::TwitchIRCClient;
use twitch_irc::{ClientConfig, MetricsConfig, SecureTCPTransport};

const WEBSERVER_LISTEN_ADDR: &str = "127.0.0.1:3000";

// This example demonstrates usage of the `metrics-collection` feature flag.
// `metrics-collection` enables a set of metrics to be exported from the client.
// See the documentation on `ClientConfig` and `MetricsConfig` for details.
//
// Creates a web server at 127.0.0.1:3000. GET http://127.0.0.1:3000/metrics to see the current set of metrics
// exported by the client.
#[tokio::main]
pub async fn main() {
tracing_subscriber::fmt::init();

let config = ClientConfig {
// Enable metrics collection.
metrics_config: MetricsConfig::Enabled {
// These labels are added to all metrics exported by the client.
// If your app has multiple twitch-irc clients, you can differentiate
// them this way, e.g. client=listener, client=second-thing, etc.
// Here we just use some exemplary extra data. You can add anything you want.
constant_labels: {
let mut labels = HashMap::new();
labels.insert("app".to_owned(), "metrics-example".to_owned());
labels.insert("version".to_owned(), env!("CARGO_PKG_VERSION").to_owned());
labels
},
// `None` specifies that metrics are to be registered with the global registry from the prometheus crate
metrics_registry: None,
},
// rest of the config is default
..ClientConfig::default()
};
let (mut incoming_messages, client) =
TwitchIRCClient::<SecureTCPTransport, StaticLoginCredentials>::new(config);

let message_handler = tokio::spawn(async move {
while let Some(message) = incoming_messages.recv().await {
tracing::info!("Received message: {:?}", message);
}
});
client.join("sodapoppin".to_owned()).unwrap();

let web_app = Router::new().route("/metrics", get(get_metrics));
let web_server = tokio::spawn(
axum::Server::bind(&WEBSERVER_LISTEN_ADDR.parse().unwrap())
.serve(web_app.into_make_service()),
);
tracing::info!("Listening for requests at {WEBSERVER_LISTEN_ADDR}");

web_server.await.unwrap().unwrap();
message_handler.await.unwrap();
}

// Web request handler for GET /metrics
pub async fn get_metrics() -> String {
// Export all metrics from the global registry from the prometheus crate
TextEncoder.encode_to_string(&prometheus::gather()).unwrap()
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@
//! as the TLS implementation, and will statically embed the current [Mozilla root
//! certificates][mozilla-roots] as the trusted root certificates.
//! * **`metrics-collection`** enables a set of metrics to be exported from the client. See the
//! documentation on `ClientConfig` for details.
//! documentation on `ClientConfig` for details. You may also want to see the `metrics` example.
//! * **`with-serde`** pulls in `serde` v1.0 and adds `#[derive(Serialize, Deserialize)]` to many
//! structs. This feature flag is automatically enabled when using any of the `refreshing-token`
//! feature flags.
Expand Down

0 comments on commit b525dc8

Please sign in to comment.