Crate tracing_capture

source ·
Expand description

Capturing tracing spans and events, e.g. for testing purposes.

The core type in this crate is CaptureLayer, a tracing Layer that can be used to capture tracing spans and events.

§Examples

use tracing::Level;
use tracing_subscriber::layer::SubscriberExt;
use tracing_capture::{CaptureLayer, SharedStorage};

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

// Capture tracing information.
tracing::subscriber::with_default(subscriber, || {
    tracing::info_span!("test", num = 42_i64).in_scope(|| {
        tracing::warn!("I feel disturbance in the Force...");
    });
});

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

// Inspect the only event in the span.
let event = span.events().next().unwrap();
assert_eq!(*event.metadata().level(), Level::WARN);
assert_eq!(
    event.message(),
    Some("I feel disturbance in the Force...")
);

§Alternatives / similar tools

  • tracing-test is a lower-level alternative.
  • tracing-fluent-assertions is more similar in its goals, but differs significantly in the API design; e.g., the assertions need to be declared before the capture.

Modules§

Structs§

Traits§