polkadot_runtime_metrics/
with_runtime_metrics.rs1const TRACING_TARGET: &'static str = "metrics";
24
25use alloc::vec::Vec;
26use codec::Encode;
27use polkadot_primitives::{
28 metric_definitions::{CounterDefinition, CounterVecDefinition, HistogramDefinition},
29 RuntimeMetricLabelValues, RuntimeMetricOp, RuntimeMetricUpdate,
30};
31
32pub struct CounterVec {
35 name: &'static str,
36}
37
38pub struct Counter {
40 name: &'static str,
41}
42
43pub struct Histogram {
44 name: &'static str,
45}
46
47trait MetricEmitter {
49 fn emit(metric_op: &RuntimeMetricUpdate) {
50 sp_tracing::event!(
51 target: TRACING_TARGET,
52 sp_tracing::Level::TRACE,
53 update_op = bs58::encode(&metric_op.encode()).into_string().as_str()
54 );
55 }
56}
57
58pub struct LabeledMetric {
60 name: &'static str,
61 label_values: RuntimeMetricLabelValues,
62}
63
64impl LabeledMetric {
65 pub fn inc_by(&self, value: u64) {
67 let metric_update = RuntimeMetricUpdate {
68 metric_name: Vec::from(self.name),
69 op: RuntimeMetricOp::IncrementCounterVec(value, self.label_values.clone()),
70 };
71
72 Self::emit(&metric_update);
73 }
74
75 pub fn inc(&self) {
77 self.inc_by(1);
78 }
79}
80
81impl MetricEmitter for LabeledMetric {}
82impl MetricEmitter for Counter {}
83impl MetricEmitter for Histogram {}
84
85impl CounterVec {
86 pub const fn new(definition: CounterVecDefinition) -> Self {
89 CounterVec { name: definition.name }
92 }
93
94 pub fn with_label_values(&self, label_values: &[&'static str]) -> LabeledMetric {
97 LabeledMetric { name: self.name, label_values: label_values.into() }
98 }
99}
100
101impl Counter {
102 pub const fn new(definition: CounterDefinition) -> Self {
105 Counter { name: definition.name }
106 }
107
108 pub fn inc_by(&self, value: u64) {
110 let metric_update = RuntimeMetricUpdate {
111 metric_name: Vec::from(self.name),
112 op: RuntimeMetricOp::IncrementCounter(value),
113 };
114
115 Self::emit(&metric_update);
116 }
117
118 pub fn inc(&self) {
120 self.inc_by(1);
121 }
122}
123
124impl Histogram {
125 pub const fn new(definition: HistogramDefinition) -> Self {
128 Histogram { name: definition.name }
131 }
132
133 pub fn observe(&self, value: u128) {
135 let metric_update = RuntimeMetricUpdate {
136 metric_name: Vec::from(self.name),
137 op: RuntimeMetricOp::ObserveHistogram(value),
138 };
139 Self::emit(&metric_update);
140 }
141}
142
143pub fn get_current_time() -> u128 {
145 frame_benchmarking::current_time()
146}