Testing your telemetry
Telemetry is part of what a function does. Dashboards and alerts depend on a span’s name, a metric’s attributes, a failure being marked as one. A unit test can check them like any other result.
These tests run a function with its spans and metrics kept in memory, then look at what it recorded. Nothing is installed globally and nothing is sent anywhere, so the tests run in parallel, as tests usually do.
The function
Section titled “The function”It totals an order. Each call is a span, marked as an error when the order is rejected, and is counted by outcome:
/// The total of an order, in cents. An order needs at least one item.////// Each call is a span, `place_order`, marked as an error when the order is/// rejected, and counted in `orders` by outcome.#[tracing::instrument( skip(prices), fields(order.items = prices.len(), otel.status_code = tracing::field::Empty))]fn place_order(prices: &[u32]) -> Result<u32, String> { if prices.is_empty() { tracing::Span::current().record("otel.status_code", "error"); metrics::counter!("orders", "outcome" => "rejected").increment(1); return Err("an order needs at least one item".into()); } let total = prices.iter().sum(); tracing::info!(total, "placed"); metrics::counter!("orders", "outcome" => "placed").increment(1); Ok(total)}The tests
Section titled “The tests”#[cfg(test)]mod tests { use oxtel::sdk::KeyValue; use oxtel::sdk::metrics::{MeterProvider, MetricFamily, PointValue}; use oxtel::sdk::trace::{InMemorySpanExporter, Sampler, SpanData, Status, TracerProvider}; use tracing_subscriber::layer::SubscriberExt;
use super::place_order;
/// Runs `f` with this thread's spans and metrics kept in memory, and /// returns what it returned, the spans it ended and the metrics it /// recorded. fn capture<T>(f: impl FnOnce() -> T) -> (T, Vec<SpanData>, Vec<MetricFamily>) { let spans = InMemorySpanExporter::default(); let traces = TracerProvider::builder() .with_sampler(Sampler::AlwaysOn) .with_simple_exporter(spans.clone()) .build(); let meters = MeterProvider::builder().build(); let subscriber = tracing_subscriber::registry().with(traces.layer()); let result = tracing::subscriber::with_default(subscriber, || { metrics::with_local_recorder(&meters.recorder(), f) }); (result, spans.finished_spans(), meters.collect()) }
/// The `orders` counter's value for `outcome`. fn orders(metrics: &[MetricFamily], outcome: &str) -> Option<u64> { let family = metrics.iter().find(|m| m.name == "orders")?; let point = family .points .iter() .find(|p| p.attributes == [("outcome".to_string(), outcome.to_string())])?; match point.value { PointValue::Counter(n) => Some(n), _ => None, } }
#[test] fn a_placed_order_is_a_span_and_a_count() { let (result, spans, metrics) = capture(|| place_order(&[450, 1200])); assert_eq!(result, Ok(1650));
assert_eq!(spans.len(), 1); let span = &spans[0]; assert_eq!(span.name, "place_order"); assert!(span.attributes.contains(&KeyValue::new("order.items", 2))); assert_eq!(span.status, Status::Unset); // The log line written inside the span is kept as one of its events. let placed = &span.events[0]; assert_eq!(placed.name, "placed"); assert!(placed.attributes.contains(&KeyValue::new("total", 1650)));
assert_eq!(orders(&metrics, "placed"), Some(1)); assert_eq!(orders(&metrics, "rejected"), None); }
#[test] fn a_rejected_order_is_an_error() { let (result, spans, metrics) = capture(|| place_order(&[])); assert!(result.is_err());
assert!(matches!(spans[0].status, Status::Error { .. })); assert_eq!(orders(&metrics, "rejected"), Some(1)); assert_eq!(orders(&metrics, "placed"), None); }}Dependencies
Section titled “Dependencies”[dependencies]oxtel = "0.4"metrics = "0.24"tracing = "0.1"
[dev-dependencies]tracing-subscriber = { version = "0.3", default-features = false, features = ["registry"] }Run it
Section titled “Run it”From a checkout of the repository:
cargo test -p oxtel-examples --example testingCI runs these tests with the rest of the repository’s.
How it works
Section titled “How it works”- Spans.
InMemorySpanExporterkeeps each span it’s given. Withwith_simple_exporter, theTracerProvidergives it each span as the span ends, so they’re all there when the function returns.Sampler::AlwaysOnkeeps every span, whateverOTEL_TRACES_SAMPLERsays. - Log lines. The
TracerProviderkeeps a line written inside a span as one of the span’s events, so a test can check those too. - Metrics.
MeterProvider::collectreturns every metric recorded so far, each with its series, one per set of attributes. - Only this thread.
tracing::subscriber::with_defaultandmetrics::with_local_recorderapply to the current thread, until the closure returns. That keeps parallel tests apart. It also means work the function hands to other threads isn’t captured: for async code, run a single-threaded runtime inside the closure. - Failures. oxtel reads a span’s
otel.status_codefield: recording"error"marks the span as failed, as the function does for a rejected order.
In an async test, such as one with #[tokio::test], use the forms that return a guard instead of taking a closure: tracing::subscriber::set_default and metrics::set_default_local_recorder.
In a library
Section titled “In a library”A library that doesn’t depend on oxtel tests its telemetry the same way, with oxtel-sdk as a dev-dependency instead: the same types, from oxtel_sdk instead of oxtel::sdk. A library crate has more on instrumenting one.