lib.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //! # CDK Prometheus
  2. pub mod error;
  3. pub mod metrics;
  4. pub mod server;
  5. #[cfg(feature = "system-metrics")]
  6. pub mod process;
  7. // Re-exports for convenience
  8. pub use error::{PrometheusError, Result};
  9. pub use metrics::{global, CdkMetrics, METRICS};
  10. #[cfg(feature = "system-metrics")]
  11. pub use process::SystemMetrics;
  12. // Re-export prometheus crate for custom metrics
  13. pub use prometheus;
  14. pub use server::{PrometheusBuilder, PrometheusConfig, PrometheusServer};
  15. /// Macro for recording metrics with optional fallback to global instance
  16. ///
  17. /// Usage:
  18. /// ```rust
  19. /// use cdk_prometheus::record_metrics;
  20. ///
  21. /// // With optional metrics instance
  22. /// record_metrics!(metrics_option => {
  23. /// dec_in_flight_requests("operation");
  24. /// record_mint_operation("operation", true);
  25. /// });
  26. ///
  27. /// // Direct global calls
  28. /// record_metrics!({
  29. /// dec_in_flight_requests("operation");
  30. /// record_mint_operation("operation", true);
  31. /// });
  32. /// ```
  33. #[macro_export]
  34. macro_rules! record_metrics {
  35. // Pattern for using optional metrics with fallback to global
  36. ($metrics_opt:expr => { $($method:ident($($arg:expr),*));* $(;)? }) => {
  37. #[cfg(feature = "prometheus")]
  38. {
  39. if let Some(metrics) = $metrics_opt.as_ref() {
  40. $(
  41. metrics.$method($($arg),*);
  42. )*
  43. } else {
  44. $(
  45. $crate::global::$method($($arg),*);
  46. )*
  47. }
  48. }
  49. };
  50. // Pattern for using global metrics directly
  51. ({ $($method:ident($($arg:expr),*));* $(;)? }) => {
  52. #[cfg(feature = "prometheus")]
  53. {
  54. $(
  55. $crate::global::$method($($arg),*);
  56. )*
  57. }
  58. };
  59. }
  60. /// Convenience function to create a new CDK metrics instance
  61. ///
  62. /// # Errors
  63. /// Returns an error if any of the metrics cannot be created or registered
  64. pub fn create_cdk_metrics() -> Result<CdkMetrics> {
  65. CdkMetrics::new()
  66. }
  67. /// Convenience function to start a Prometheus server with specific metrics
  68. ///
  69. /// # Errors
  70. /// Returns an error if the server cannot be created or started
  71. pub async fn start_default_server_with_metrics(
  72. shutdown_signal: impl std::future::Future<Output = ()> + Send + 'static,
  73. ) -> Result<()> {
  74. let server = PrometheusBuilder::new().build_with_cdk_metrics()?;
  75. server.start(shutdown_signal).await
  76. }