lib.rs 2.4 KB

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