1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! A lightweight metrics facade.
//!
//! The `metrics` crate provides a single metrics API that abstracts over the actual metrics
//! implementation.  Libraries can use the metrics API provided by this crate, and the consumer of
//! those libraries can choose the metrics implementation that is most suitable for its use case.
//!
//! If no metrics implementation is selected, the facade falls back to a "noop" implementation that
//! ignores all metrics.  The overhead in this case is very small - an atomic load and comparison.
//!
//! # Use
//! The basic use of the facade crate is through the three metrics macros: [`counter!`], [`gauge!`],
//! and [`histogram!`].  These macros correspond to updating a counter, updating a gauge,
//! and updating a histogram.
//!
//! ## In libraries
//! Libraries should link only to the `metrics` crate, and use the provided macros to record
//! whatever metrics will be useful to downstream consumers.
//!
//! ### Examples
//!
//! ```rust
//! use metrics::{histogram, counter};
//!
//! # use std::time::Instant;
//! # pub fn run_query(_: &str) -> u64 { 42 }
//! pub fn process(query: &str) -> u64 {
//!     let start = Instant::now();
//!     let row_count = run_query(query);
//!     let delta = Instant::now() - start;
//!
//!     histogram!("process.query_time", delta);
//!     counter!("process.query_row_count", row_count);
//!
//!     row_count
//! }
//! # fn main() {}
//! ```
//!
//! ## In executables
//!
//! Executables should choose a metrics implementation and initialize it early in the runtime of
//! the program.  Metrics implementations will typically include a function to do this.  Any
//! metrics recordered before the implementation is initialized will be ignored.
//!
//! The executable itself may use the `metrics` crate to record metrics well.
//!
//! ### Warning
//!
//! The metrics system may only be initialized once.
//!
//! # Available metrics implementations
//!
//! * # Native recorder:
//!     * [metrics-exporter-tcp] - outputs metrics to clients over TCP
//!     * [metrics-exporter-prometheus] - serves a Prometheus scrape endpoint
//!
//! # Implementing a Recorder
//!
//! Recorders implement the [`Recorder`] trait.  Here's a basic example which writes the
//! metrics in text form via the `log` crate.
//!
//! ```rust
//! # use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
//! # use std::collections::HashMap;
//! use log::info;
//! use metrics::{Identifier, Key, Recorder};
//!
//! struct LogRecorder {
//!     id: AtomicUsize,
//!     keys: Mutex<HashMap<Identifier, Key>>,
//! }
//!
//! impl LogRecorder {
//!     fn register(&self, key: Key) -> Identifier {
//!         let uid = self.id.fetch_add(1, Ordering::AcqRel);
//!         let id = uid.into();
//!         let mut keys = self.keys.lock().expect("failed to lock keys");
//!         keys.insert(id, key);
//!         id
//!     }
//!
//!     fn get_key(&self, id: Identifier) -> Key {
//!         let keys = self.keys.lock().expect("failed to lock keys");
//!         keys.get(&id).expect("invalid identifier").clone()
//!     }
//! }
//!
//! impl Recorder for LogRecorder {
//!     fn register_counter(&self, key: Key, _description: Option<&'static str>) -> Identifier {
//!         self.register(key)
//!     }
//!
//!     fn register_gauge(&self, key: Key, _description: Option<&'static str>) -> Identifier {
//!         self.register(key)
//!     }
//!
//!     fn register_histogram(&self, key: Key, _description: Option<&'static str>) -> Identifier {
//!         self.register(key)
//!     }
//!
//!     fn increment_counter(&self, id: Identifier, value: u64) {
//!         let key = self.get_key(id);
//!         info!("counter '{}' -> {}", key, value);
//!     }
//!
//!     fn update_gauge(&self, id: Identifier, value: f64) {
//!         let key = self.get_key(id);
//!         info!("gauge '{}' -> {}", key, value);
//!     }
//!
//!     fn record_histogram(&self, id: Identifier, value: u64) {
//!         let key = self.get_key(id);
//!         info!("histogram '{}' -> {}", key, value);
//!     }
//! }
//! # fn main() {}
//! ```
//!
//! Recorders are installed by calling the [`set_recorder`] function.  Recorders should provide a
//! function that wraps the creation and installation of the recorder:
//!
//! ```rust
//! # use metrics::{Recorder, Key, Identifier};
//! # struct LogRecorder;
//! # impl Recorder for LogRecorder {
//! #     fn register_counter(&self, _key: Key, _description: Option<&'static str>) -> Identifier { Identifier::default() }
//! #     fn register_gauge(&self, _key: Key, _description: Option<&'static str>) -> Identifier { Identifier::default() }
//! #     fn register_histogram(&self, _key: Key, _description: Option<&'static str>) -> Identifier { Identifier::default() }
//! #     fn increment_counter(&self, _id: Identifier, _value: u64) {}
//! #     fn update_gauge(&self, _id: Identifier, _value: f64) {}
//! #     fn record_histogram(&self, _id: Identifier, _value: u64) {}
//! # }
//! use metrics::SetRecorderError;
//!
//! static RECORDER: LogRecorder = LogRecorder;
//!
//! pub fn init() -> Result<(), SetRecorderError> {
//!     metrics::set_recorder(&RECORDER)
//! }
//! # fn main() {}
//! ```
//!
//! # Use with `std`
//!
//! `set_recorder` requires you to provide a `&'static Recorder`, which can be hard to
//! obtain if your recorder depends on some runtime configuration.  The `set_boxed_recorder`
//! function is available with the `std` Cargo feature.  It is identical to `set_recorder` except
//! that it takes a `Box<Recorder>` rather than a `&'static Recorder`:
//!
//! ```rust
//! # use metrics::{Recorder, Key, Identifier};
//! # struct LogRecorder;
//! # impl Recorder for LogRecorder {
//! #     fn register_counter(&self, _key: Key, _description: Option<&'static str>) -> Identifier { Identifier::default() }
//! #     fn register_gauge(&self, _key: Key, _description: Option<&'static str>) -> Identifier { Identifier::default() }
//! #     fn register_histogram(&self, _key: Key, _description: Option<&'static str>) -> Identifier { Identifier::default() }
//! #     fn increment_counter(&self, _id: Identifier, _value: u64) {}
//! #     fn update_gauge(&self, _id: Identifier, _value: f64) {}
//! #     fn record_histogram(&self, _id: Identifier, _value: u64) {}
//! # }
//! use metrics::SetRecorderError;
//!
//! # #[cfg(feature = "std")]
//! pub fn init() -> Result<(), SetRecorderError> {
//!     metrics::set_boxed_recorder(Box::new(LogRecorder))
//! }
//! # fn main() {}
//! ```
//!
//! [metrics-exporter-tcp]: https://docs.rs/metrics-exporter-tcp
//! [metrics-exporter-prometheus]: https://docs.rs/metrics-exporter-prometheus
#![deny(missing_docs)]
use proc_macro_hack::proc_macro_hack;

mod common;
pub use self::common::*;

mod key;
pub use self::key::*;

mod label;
pub use self::label::*;

mod recorder;
pub use self::recorder::*;

/// Registers a counter.
///
/// Counters represent a single value that can only be incremented over time, or reset to zero.
///
/// Metrics can be registered with an optional description.  Whether or not the installed recorder
/// does anything with the description is implementation defined.  Labels can also be specified
/// when registering a metric.
///
/// Counters, when registered, start at zero.
///
/// # Scoped versus unscoped
/// Metrics can be unscoped or scoped, where the scoping is derived by the current module the call
/// is taking place in.  This scope is used as a prefix to the provided metric name.
///
/// # Example
/// ```
/// # use metrics::register_counter;
/// # fn main() {
/// // A regular, unscoped counter:
/// register_counter!("some_metric_name");
///
/// // A scoped counter.  This inherits a scope derived by the current module:
/// register_counter!(<"some_metric_name">);
///
/// // Providing a description for a counter:
/// register_counter!("some_metric_name", "number of woopsy daisies");
///
/// // Specifying labels:
/// register_counter!("some_metric_name", "service" => "http");
///
/// // And all combined:
/// register_counter!("some_metric_name", "number of woopsy daisies", "service" => "http");
/// register_counter!(<"some_metric_name">, "number of woopsy daisies", "service" => "http");
///
/// // And just for an alternative form of passing labels:
/// let dynamic_val = "woo";
/// let labels = [("dynamic_key", format!("{}!", dynamic_val))];
/// register_counter!("some_metric_name", &labels);
/// # }
/// ```
#[proc_macro_hack]
pub use metrics_macros::register_counter;

/// Registers a gauge.
///
/// Gauges represent a single value that can go up or down over time.
///
/// Metrics can be registered with an optional description.  Whether or not the installed recorder
/// does anything with the description is implementation defined.  Labels can also be specified
/// when registering a metric.
///
/// Gauges, when registered, start at zero.
///
/// # Scoped versus unscoped
/// Metrics can be unscoped or scoped, where the scoping is derived by the current module the call
/// is taking place in.  This scope is used as a prefix to the provided metric name.
///
/// # Example
/// ```
/// # use metrics::register_gauge;
/// # fn main() {
/// // A regular, unscoped gauge:
/// register_gauge!("some_metric_name");
///
/// // A scoped gauge.  This inherits a scope derived by the current module:
/// register_gauge!(<"some_metric_name">);
///
/// // Providing a description for a gauge:
/// register_gauge!("some_metric_name", "number of woopsy daisies");
///
/// // Specifying labels:
/// register_gauge!("some_metric_name", "service" => "http");
///
/// // And all combined:
/// register_gauge!("some_metric_name", "number of woopsy daisies", "service" => "http");
/// register_gauge!(<"some_metric_name">, "number of woopsy daisies", "service" => "http");
///
/// // And just for an alternative form of passing labels:
/// let dynamic_val = "woo";
/// let labels = [("dynamic_key", format!("{}!", dynamic_val))];
/// register_gauge!("some_metric_name", &labels);
/// # }
/// ```
#[proc_macro_hack]
pub use metrics_macros::register_gauge;

/// Records a histogram.
///
/// Histograms measure the distribution of values for a given set of measurements.
///
/// Metrics can be registered with an optional description.  Whether or not the installed recorder
/// does anything with the description is implementation defined.  Labels can also be specified
/// when registering a metric.
///
/// Histograms, when registered, start at zero.
///
/// # Scoped versus unscoped
/// Metrics can be unscoped or scoped, where the scoping is derived by the current module the call
/// is taking place in.  This scope is used as a prefix to the provided metric name.
///
/// # Example
/// ```
/// # use metrics::register_histogram;
/// # fn main() {
/// // A regular, unscoped histogram:
/// register_histogram!("some_metric_name");
///
/// // A scoped histogram.  This inherits a scope derived by the current module:
/// register_histogram!(<"some_metric_name">);
///
/// // Providing a description for a histogram:
/// register_histogram!("some_metric_name", "number of woopsy daisies");
///
/// // Specifying labels:
/// register_histogram!("some_metric_name", "service" => "http");
///
/// // And all combined:
/// register_histogram!("some_metric_name", "number of woopsy daisies", "service" => "http");
/// register_histogram!(<"some_metric_name">, "number of woopsy daisies", "service" => "http");
///
/// // And just for an alternative form of passing labels:
/// let dynamic_val = "woo";
/// let labels = [("dynamic_key", format!("{}!", dynamic_val))];
/// register_histogram!("some_metric_name", &labels);
/// # }
/// ```
#[proc_macro_hack]
pub use metrics_macros::register_histogram;

/// Increments a counter.
///
/// Counters represent a single value that can only be incremented over time, or reset to zero.
///
/// # Scoped versus unscoped
/// Metrics can be unscoped or scoped, where the scoping is derived by the current module the call
/// is taking place in.  This scope is used as a prefix to the provided metric name.
///
/// # Example
/// ```
/// # use metrics::increment;
/// # fn main() {
/// // A regular, unscoped increment:
/// increment!("some_metric_name");
///
/// // A scoped increment.  This inherits a scope derived by the current module:
/// increment!(<"some_metric_name">);
///
/// // Specifying labels:
/// increment!("some_metric_name", "service" => "http");
///
/// // And all combined:
/// increment!("some_metric_name", "service" => "http");
/// increment!(<"some_metric_name">, "service" => "http");
///
/// // And just for an alternative form of passing labels:
/// let dynamic_val = "woo";
/// let labels = [("dynamic_key", format!("{}!", dynamic_val))];
/// increment!("some_metric_name", &labels);
/// # }
/// ```
#[proc_macro_hack]
pub use metrics_macros::increment;

/// Increments a counter.
///
/// Counters represent a single value that can only be incremented over time, or reset to zero.
///
/// # Scoped versus unscoped
/// Metrics can be unscoped or scoped, where the scoping is derived by the current module the call
/// is taking place in.  This scope is used as a prefix to the provided metric name.
///
/// # Example
/// ```
/// # use metrics::counter;
/// # fn main() {
/// // A regular, unscoped counter:
/// counter!("some_metric_name", 12);
///
/// // A scoped counter.  This inherits a scope derived by the current module:
/// counter!(<"some_metric_name">, 12);
///
/// // Specifying labels:
/// counter!("some_metric_name", 12, "service" => "http");
///
/// // And all combined:
/// counter!("some_metric_name", 12, "service" => "http");
/// counter!(<"some_metric_name">, 12, "service" => "http");
///
/// // And just for an alternative form of passing labels:
/// let dynamic_val = "woo";
/// let labels = [("dynamic_key", format!("{}!", dynamic_val))];
/// counter!("some_metric_name", 12, &labels);
/// # }
/// ```
#[proc_macro_hack]
pub use metrics_macros::counter;

/// Updates a gauge.
///
/// Gauges represent a single value that can go up or down over time.
///
/// # Scoped versus unscoped
/// Metrics can be unscoped or scoped, where the scoping is derived by the current module the call
/// is taking place in.  This scope is used as a prefix to the provided metric name.
///
/// # Example
/// ```
/// # use metrics::gauge;
/// # fn main() {
/// // A regular, unscoped gauge:
/// gauge!("some_metric_name", 42.2222);
///
/// // A scoped gauge.  This inherits a scope derived by the current module:
/// gauge!(<"some_metric_name">, 33.3333);
///
/// // Specifying labels:
/// gauge!("some_metric_name", 66.6666, "service" => "http");
///
/// // And all combined:
/// gauge!("some_metric_name", 55.5555, "service" => "http");
/// gauge!(<"some_metric_name">, 11.1111, "service" => "http");
///
/// // And just for an alternative form of passing labels:
/// let dynamic_val = "woo";
/// let labels = [("dynamic_key", format!("{}!", dynamic_val))];
/// gauge!("some_metric_name", 42.42, &labels);
/// # }
/// ```
#[proc_macro_hack]
pub use metrics_macros::gauge;

/// Records a histogram.
///
/// Histograms measure the distribution of values for a given set of measurements.
///
/// # Scoped versus unscoped
/// Metrics can be unscoped or scoped, where the scoping is derived by the current module the call
/// is taking place in.  This scope is used as a prefix to the provided metric name.
///
/// # Implicit conversions
/// Histograms are represented as `u64` values, but often come from another source, such as a time
/// measurement.  By default, `histogram!` will accept a `u64` directly or a
/// [`Duration`](std::time::Duration), which uses the nanoseconds total as the converted value.
///
/// External libraries and applications can create their own conversions by implementing the
/// [`IntoU64`] trait for their types, which is required for the value being passed to `histogram!`.
///
/// # Example
/// ```
/// # use metrics::histogram;
/// # use std::time::Duration;
/// # fn main() {
/// // A regular, unscoped histogram:
/// histogram!("some_metric_name", 34);
///
/// // An implicit conversion from `Duration`:
/// let d = Duration::from_millis(17);
/// histogram!("some_metric_name", d);
///
/// // A scoped histogram.  This inherits a scope derived by the current module:
/// histogram!(<"some_metric_name">, 38);
/// histogram!(<"some_metric_name">, d);
///
/// // Specifying labels:
/// histogram!("some_metric_name", 38, "service" => "http");
///
/// // And all combined:
/// histogram!("some_metric_name", d, "service" => "http");
/// histogram!(<"some_metric_name">, 57, "service" => "http");
///
/// // And just for an alternative form of passing labels:
/// let dynamic_val = "woo";
/// let labels = [("dynamic_key", format!("{}!", dynamic_val))];
/// histogram!("some_metric_name", 1337, &labels);
/// # }
/// ```
#[proc_macro_hack]
pub use metrics_macros::histogram;