metrics.rs (3353B)
1 use std::sync::OnceLock; 2 3 use opentelemetry::{ 4 global, 5 metrics::{Counter, Histogram}, 6 }; 7 8 /// Collection of order-related metric instruments. 9 pub struct OrdersMetrics { 10 /// Total number of checkout attempts (success + failure) 11 pub checkout_attempts: Counter<u64>, 12 /// Total number of failed checkouts, broken down by failure.reason 13 pub checkout_failures: Counter<u64>, 14 /// Wall-clock time to complete a checkout (seconds) 15 pub checkout_duration: Histogram<f64>, 16 /// Dollar amount of each completed order 17 pub order_total_amount: Histogram<f64>, 18 /// Number of line items per order 19 pub order_items_count: Histogram<u64>, 20 21 // Business KPI metrics: Conversion funnel 22 /// Checkout funnel started (order creation initiated) 23 pub funnel_started: Counter<u64>, 24 /// Checkout funnel reached payment validation 25 pub funnel_payment_info: Counter<u64>, 26 /// Checkout funnel completed successfully 27 pub funnel_completed: Counter<u64>, 28 29 // Business KPI metrics: Time tracking 30 /// Time from checkout start to completion 31 pub time_to_checkout: Histogram<f64>, 32 } 33 34 /// Singleton storage for the metrics instruments. 35 static METRICS: OnceLock<OrdersMetrics> = OnceLock::new(); 36 37 /// Returns a reference to the lazily-initialized orders metrics. 38 pub fn metrics() -> &'static OrdersMetrics { 39 METRICS.get_or_init(|| { 40 let meter = global::meter("orders-service"); 41 42 OrdersMetrics { 43 checkout_attempts: meter 44 .u64_counter("orders.checkout.attempts") 45 .with_description("Total checkout attempts") 46 .build(), 47 checkout_failures: meter 48 .u64_counter("orders.checkout.failures") 49 .with_description("Total failed checkouts") 50 .build(), 51 checkout_duration: meter 52 .f64_histogram("orders.checkout.duration") 53 .with_description("Time to complete checkout") 54 .with_unit("s") 55 .build(), 56 order_total_amount: meter 57 .f64_histogram("orders.total.amount") 58 .with_description("Order total in dollars") 59 .with_unit("USD") 60 .build(), 61 order_items_count: meter 62 .u64_histogram("orders.items.count") 63 .with_description("Number of items per order") 64 .build(), 65 66 // Business KPI metrics: Conversion funnel 67 funnel_started: meter 68 .u64_counter("checkout.funnel.started") 69 .with_description("Checkout attempts initiated") 70 .build(), 71 funnel_payment_info: meter 72 .u64_counter("checkout.funnel.payment_info") 73 .with_description("Checkout reached payment validation") 74 .build(), 75 funnel_completed: meter 76 .u64_counter("checkout.funnel.completed") 77 .with_description("Checkout successfully completed") 78 .build(), 79 80 // Business KPI metrics: Time tracking 81 time_to_checkout: meter 82 .f64_histogram("checkout.time_to_completion") 83 .with_description("Time from checkout start to completion") 84 .with_unit("s") 85 .build(), 86 } 87 }) 88 }