diff --git a/CHANGELOG.md b/CHANGELOG.md index 5278554..65db309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Cargo.toml b/Cargo.toml index a109eb7..2f73a9a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" @@ -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"] diff --git a/examples/metrics.rs b/examples/metrics.rs new file mode 100644 index 0000000..1872087 --- /dev/null +++ b/examples/metrics.rs @@ -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::::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() +} diff --git a/src/lib.rs b/src/lib.rs index 036ab1b..bbde59e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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.