Capturing Tracing Spans and Events

Build Status License: MIT OR Apache-2.0 rust 1.60+ required

Documentation: crate docs (main)

This crate provides a [tracing] [Layer] to capture tracing spans and events as they occur. The captured spans and events can then be used for testing assertions (e.g., "Did a span with a specific name / target / … occur? What were its fields? Was the span closed? How many times the span was entered?" and so on).

The crate supports both straightforward assertions on the captured data, and more fluent assertions based on [predicates].

Usage

Add this to your Crate.toml:

toml [dependencies] tracing-capture = "0.1.0"

Capturing spans for test assertions

```rust use tracing::Level; use tracingsubscriber::layer::SubscriberExt; use tracingcapture::{CaptureLayer, SharedStorage};

let subscriber = tracingsubscriber::fmt() .pretty() .withmax_level(Level::INFO) .finish(); // Add the capturing layer. let storage = SharedStorage::default(); let subscriber = subscriber.with(CaptureLayer::new(&storage));

// Capture tracing information. tracing::subscriber::withdefault(subscriber, || { tracing::infospan!("test", num = 42i64).inscope(|| { tracing::warn!("I feel disturbance in the Force..."); }); });

// Inspect the only captured span. let storage = storage.lock(); asserteq!(storage.allspans().len(), 1); let span = storage.allspans().next().unwrap(); asserteq!(span["num"], 42i64); asserteq!(span.stats().entered, 1); assert!(span.stats().is_closed); ```

Predicate-based assertions

```rust use predicates::str::contains; use tracing::Level; use tracingsubscriber::{layer::SubscriberExt, Registry}; use tracingcapture::{predicates::*, CaptureLayer, SharedStorage};

let storage = SharedStorage::default(); let subscriber = Registry::default().with(CaptureLayer::new(&storage)); tracing::subscriber::withdefault(subscriber, || { tracing::infospan!("testspans").inscope(|| { tracing::warn!(result = 42_i64, "computed"); }); });

let storage = storage.lock(); let predicate = level(Level::WARN) & message(contains("compute")) & field("result", 42i64); // Checks that there is a single event satisfying predicate. storage.scanevents().single(&predicate); // ...and that none of spans satisfy similar predicate. storage.scan_spans().none(&level(Level::WARN)); ```

Alternatives / similar tools

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in tracing-toolbox by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.