Skip to main content

metrics_exporter_csv/
lib.rs

1//! CSV exporter for the `metrics` crate.
2//!
3//! This crate provides a [`CsvRecorder`] that implements [`metrics::Recorder`],
4//! plus a [`CsvBuilder`] for configuration and installation.
5//! Output is long-form CSV with a fixed header: `timestamp_rfc3339,name,kind,labels,value`.
6//! The `name` field is the sanitized metric name. The `labels` field is a `|`-delimited list of
7//! `key=value` pairs in the order provided by the metrics key. Components are lowercased and
8//! whitespace plus `|`/`=` characters are normalized to underscores.
9//! It can be installed directly or composed with other recorders using `metrics-util` fanout
10//! layers.
11//!
12//! Locally recorded histograms are summarized into quantiles. Each
13//! histogram emits one row per statistic, with the statistic carried in the `labels` field as a
14//! `stat=<name>` pair and a scalar in the `value` field. Finite samples feed a DDSketch quantile
15//! summary that produces `count`, `min`, `q50`/`q90`/`q95`/`q99`/`q999`, and `max` (values
16//! formatted to 6 decimals). `count` is always emitted, so a registered histogram with no samples
17//! still produces a `stat=count` row with value `0`. Non-finite samples are reported as `-inf`,
18//! `inf`, and `nan` counts.
19//! Local histogram buckets are cleared after each snapshot, so quantiles describe the samples recorded
20//! since the previous flush interval.
21//!
22//! The output file is created immediately when the recorder is constructed. The base output path
23//! must not already exist; creation fails if it does. The CSV header is written once on creation.
24//!
25//! ## Output format
26//! ```text
27//! timestamp_rfc3339,name,kind,labels,value
28//! 2026-01-08T12:00:00.123Z,requests_total,counter,method=get,42
29//! 2026-01-08T12:00:00.123Z,temperature,gauge,,21.400000
30//! 2026-01-08T12:00:00.123Z,latency_ms,histogram,stat=count,8
31//! 2026-01-08T12:00:00.123Z,latency_ms,histogram,stat=q50,1.500000
32//! 2026-01-08T12:00:00.123Z,latency_ms,histogram,stat=q99,2.000000
33//! ```
34//!
35//! ## Name and label encoding
36//! ```text
37//! http_requests_total
38//! method=get|status=200
39//! ```
40//!
41//! Labels are emitted in the order provided by the metrics key. Components are lowercased, and
42//! whitespace plus `|`/`=` are normalized to underscores.
43//!
44//! ## Basic usage (Smol runtime)
45//! ```no_run
46//! use std::{time::Duration};
47//! use metrics_exporter_csv::{CsvBuilder};
48//!
49//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
50//! let (recorder, exporter) = CsvBuilder::default()
51//!     .with_path("metrics.csv")
52//!     .with_flush_interval(Duration::from_secs(3))
53//!     .build()
54//!     .expect("build recorder");
55//!
56//! metrics::set_global_recorder(recorder).expect("install recorder");
57//! smol::spawn(exporter);
58//! # Ok(())
59//! # }
60//! ```
61//!
62//! ## Deterministic shutdown
63//! Drop the recorder to request a final flush. The exporter future should be allowed to run
64//! until it completes.
65//!
66//! ## Runtime requirement
67//! `CsvBuilder::build` returns an exporter future that must be driven by a Smol executor (for
68//! example via `smol::spawn` or `smol::block_on`). `CsvBuilder::install` spawns a background
69//! thread that runs a single-threaded Smol executor to drive the exporter future and returns
70//! once the thread is started.
71//!
72//! When built with the `tokio` feature, `CsvBuilder::install_with_tokio` spawns the exporter
73//! future onto the current Tokio runtime.
74
75mod error;
76#[cfg(feature = "prometheus")]
77mod prometheus;
78mod recorder;
79mod snapshot;
80mod util;
81
82pub use crate::{
83    error::{BuildError, CsvError},
84    recorder::{CsvBuilder, CsvRecorder, ExporterFuture},
85};
86
87#[cfg(feature = "prometheus")]
88pub use prometheus::SnapshotSource;