Skip to main content

tpt_log_tap/
lib.rs

1//! Per-test structured [`tracing`] event capture — assert on **field values**,
2//! not on formatted log text.
3//!
4//! `tpt-log-tap` installs a per-thread [`tracing`] subscriber for the duration of
5//! a test, records every event (level, target, message, and structured fields)
6//! into an in-memory buffer, and lets you assert on those fields directly. When
7//! the returned [`TapGuard`] is dropped the subscriber is uninstalled, so tests
8//! stay isolated even when run in parallel.
9//!
10//! # Why field-level assertions?
11//!
12//! Matching on rendered log strings is brittle: formatting, ANSI colour, and
13//! field ordering all change the text. Instead, capture the event and assert on
14//! the values you care about:
15//!
16//! ```
17//! use tpt_log_tap::LogTap;
18//! use tracing::Level;
19//!
20//! let tap = LogTap::new().install();
21//!
22//! tracing::info!(user_id = 42, action = "login", "user signed in");
23//!
24//! tap.assert_contains(Level::INFO, "", &[("user_id", "42"), ("action", "login")]);
25//! ```
26//!
27//! # Isolation across parallel tests
28//!
29//! [`LogTap::install`] uses [`tracing::subscriber::set_default`], which scopes the
30//! subscriber to the **current thread**. Each test therefore captures only its
31//! own events, even under `cargo test`'s default parallelism. (For `async` tests
32//! that hop threads, keep the traced work on the test's thread — see the crate
33//! README for details.)
34
35use std::fmt;
36use std::sync::{Arc, Mutex};
37
38use tracing::field::{Field, Visit};
39use tracing::subscriber::DefaultGuard;
40use tracing::{Level, Metadata, Subscriber};
41use tracing_subscriber::layer::{Context, SubscriberExt};
42use tracing_subscriber::registry::Registry;
43use tracing_subscriber::Layer;
44
45/// A single captured tracing event.
46#[derive(Debug, Clone)]
47pub struct CapturedEvent {
48    /// The event's verbosity level.
49    pub level: Level,
50    /// The event's target (usually the module path).
51    pub target: String,
52    /// The event's `message` field, if present, rendered to a string.
53    pub message: Option<String>,
54    /// All structured fields (including `message`) as `(name, value)` pairs.
55    ///
56    /// Values are the `Debug`/`Display` rendering of each field, with surrounding
57    /// quotes stripped from string values so `field = "x"` compares as `"x"`.
58    pub fields: Vec<(String, String)>,
59}
60
61impl CapturedEvent {
62    /// Look up a field's captured value by name.
63    pub fn field(&self, name: &str) -> Option<&str> {
64        self.fields
65            .iter()
66            .find(|(k, _)| k == name)
67            .map(|(_, v)| v.as_str())
68    }
69
70    /// Returns `true` if this event has every `(name, value)` pair in `fields`.
71    pub fn has_fields(&self, fields: &[(&str, &str)]) -> bool {
72        fields
73            .iter()
74            .all(|(k, v)| self.field(k).is_some_and(|actual| actual == *v))
75    }
76}
77
78/// Shared, thread-safe buffer of captured events.
79type Buffer = Arc<Mutex<Vec<CapturedEvent>>>;
80
81/// Builder for a log tap.
82///
83/// Configure an optional minimum level and target filter, then call
84/// [`install`](LogTap::install) to activate capture for the current thread.
85#[derive(Debug, Clone, Default)]
86pub struct LogTap {
87    max_level: Option<Level>,
88    target_prefix: Option<String>,
89}
90
91impl LogTap {
92    /// Create a new tap that captures **all** events at every level and target.
93    pub fn new() -> Self {
94        Self::default()
95    }
96
97    /// Only capture events at or above `level` (more verbose than this are
98    /// dropped). For example, `level(Level::WARN)` keeps `WARN` and `ERROR`.
99    pub fn level(mut self, level: Level) -> Self {
100        self.max_level = Some(level);
101        self
102    }
103
104    /// Only capture events whose target starts with `prefix`.
105    ///
106    /// Useful for isolating your crate's events from dependency noise, e.g.
107    /// `target("my_crate")`.
108    pub fn target(mut self, prefix: impl Into<String>) -> Self {
109        self.target_prefix = Some(prefix.into());
110        self
111    }
112
113    /// Install the tap as the current thread's default subscriber and start
114    /// capturing.
115    ///
116    /// The returned [`TapGuard`] must be kept alive for the duration of the
117    /// test; dropping it uninstalls the subscriber.
118    pub fn install(self) -> TapGuard {
119        let buffer: Buffer = Arc::new(Mutex::new(Vec::new()));
120        let layer = CaptureLayer {
121            buffer: Arc::clone(&buffer),
122            max_level: self.max_level,
123            target_prefix: self.target_prefix,
124        };
125        let subscriber = Registry::default().with(layer);
126        let guard = tracing::subscriber::set_default(subscriber);
127        TapGuard {
128            buffer,
129            _guard: guard,
130            pending: Vec::new(),
131        }
132    }
133}
134
135/// RAII guard that keeps the per-thread subscriber installed and exposes the
136/// captured events for assertions.
137///
138/// Dropping the guard uninstalls the subscriber and verifies any expectations
139/// registered via [`expect_contains`](TapGuard::expect_contains).
140pub struct TapGuard {
141    buffer: Buffer,
142    _guard: DefaultGuard,
143    pending: Vec<Expectation>,
144}
145
146#[derive(Debug, Clone)]
147struct Expectation {
148    level: Level,
149    target: String,
150    fields: Vec<(String, String)>,
151}
152
153impl TapGuard {
154    /// Snapshot of all events captured so far, in emission order.
155    pub fn events(&self) -> Vec<CapturedEvent> {
156        self.buffer.lock().expect("log-tap buffer poisoned").clone()
157    }
158
159    /// Number of events captured so far.
160    pub fn len(&self) -> usize {
161        self.buffer.lock().expect("log-tap buffer poisoned").len()
162    }
163
164    /// Returns `true` if no events have been captured.
165    pub fn is_empty(&self) -> bool {
166        self.buffer
167            .lock()
168            .expect("log-tap buffer poisoned")
169            .is_empty()
170    }
171
172    /// Returns `true` if any captured event matches `level`, `target` (empty
173    /// string = any target), and contains all the given `fields`.
174    pub fn contains(&self, level: Level, target: &str, fields: &[(&str, &str)]) -> bool {
175        self.events()
176            .iter()
177            .any(|e| event_matches(e, level, target, fields))
178    }
179
180    /// Assert that at least one captured event matches `level`, `target`
181    /// (`""` = any target), and contains all the given `fields`.
182    ///
183    /// # Panics
184    ///
185    /// Panics with a diagnostic listing the captured events if no match is found.
186    #[track_caller]
187    pub fn assert_contains(&self, level: Level, target: &str, fields: &[(&str, &str)]) {
188        if !self.contains(level, target, fields) {
189            panic!(
190                "log-tap: expected an event {}\nbut captured events were:\n{}",
191                describe_expectation(level, target, fields),
192                self.render_events()
193            );
194        }
195    }
196
197    /// Assert that **no** captured event matches `level`, `target` (`""` = any
198    /// target), and the given `fields`.
199    ///
200    /// # Panics
201    ///
202    /// Panics if a matching event is found.
203    #[track_caller]
204    pub fn assert_not_contains(&self, level: Level, target: &str, fields: &[(&str, &str)]) {
205        if self.contains(level, target, fields) {
206            panic!(
207                "log-tap: expected NO event {}\nbut captured events were:\n{}",
208                describe_expectation(level, target, fields),
209                self.render_events()
210            );
211        }
212    }
213
214    /// Register an expectation checked automatically when the guard is dropped.
215    ///
216    /// This is handy for "this must be logged by the end of the test" assertions
217    /// without an explicit call at the end.
218    pub fn expect_contains(&mut self, level: Level, target: &str, fields: &[(&str, &str)]) {
219        self.pending.push(Expectation {
220            level,
221            target: target.to_owned(),
222            fields: fields
223                .iter()
224                .map(|(k, v)| (k.to_string(), v.to_string()))
225                .collect(),
226        });
227    }
228
229    fn render_events(&self) -> String {
230        let events = self.events();
231        if events.is_empty() {
232            return "  (none)".to_string();
233        }
234        events
235            .iter()
236            .map(|e| {
237                let fields = e
238                    .fields
239                    .iter()
240                    .map(|(k, v)| format!("{k}={v:?}"))
241                    .collect::<Vec<_>>()
242                    .join(", ");
243                format!("  [{}] {} {{ {} }}", e.level, e.target, fields)
244            })
245            .collect::<Vec<_>>()
246            .join("\n")
247    }
248}
249
250impl Drop for TapGuard {
251    fn drop(&mut self) {
252        if self.pending.is_empty() {
253            return;
254        }
255        // Don't double-panic if we're already unwinding.
256        if std::thread::panicking() {
257            return;
258        }
259        let events = self.events();
260        let unmet: Vec<&Expectation> = self
261            .pending
262            .iter()
263            .filter(|exp| {
264                let refs: Vec<(&str, &str)> = exp
265                    .fields
266                    .iter()
267                    .map(|(k, v)| (k.as_str(), v.as_str()))
268                    .collect();
269                !events
270                    .iter()
271                    .any(|e| event_matches(e, exp.level, &exp.target, &refs))
272            })
273            .collect();
274        if !unmet.is_empty() {
275            let details = unmet
276                .iter()
277                .map(|exp| {
278                    let refs: Vec<(&str, &str)> = exp
279                        .fields
280                        .iter()
281                        .map(|(k, v)| (k.as_str(), v.as_str()))
282                        .collect();
283                    format!(
284                        "  - {}",
285                        describe_expectation(exp.level, &exp.target, &refs)
286                    )
287                })
288                .collect::<Vec<_>>()
289                .join("\n");
290            panic!("log-tap: unmet pending expectations on drop:\n{details}");
291        }
292    }
293}
294
295fn event_matches(
296    event: &CapturedEvent,
297    level: Level,
298    target: &str,
299    fields: &[(&str, &str)],
300) -> bool {
301    event.level == level
302        && (target.is_empty() || event.target == target)
303        && event.has_fields(fields)
304}
305
306fn describe_expectation(level: Level, target: &str, fields: &[(&str, &str)]) -> String {
307    let target = if target.is_empty() {
308        "<any target>".to_string()
309    } else {
310        format!("target `{target}`")
311    };
312    let fields = if fields.is_empty() {
313        "<no field constraints>".to_string()
314    } else {
315        fields
316            .iter()
317            .map(|(k, v)| format!("{k}={v:?}"))
318            .collect::<Vec<_>>()
319            .join(", ")
320    };
321    format!("at level {level} for {target} with fields {{ {fields} }}")
322}
323
324// ── The capturing layer ────────────────────────────────────────────────────
325
326struct CaptureLayer {
327    buffer: Buffer,
328    max_level: Option<Level>,
329    target_prefix: Option<String>,
330}
331
332impl CaptureLayer {
333    fn accepts(&self, meta: &Metadata<'_>) -> bool {
334        if let Some(max) = self.max_level {
335            // Lower `Level` value == higher severity; `<=` keeps at-or-above.
336            if *meta.level() > max {
337                return false;
338            }
339        }
340        if let Some(prefix) = &self.target_prefix {
341            if !meta.target().starts_with(prefix.as_str()) {
342                return false;
343            }
344        }
345        true
346    }
347}
348
349impl<S: Subscriber> Layer<S> for CaptureLayer {
350    fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
351        let meta = event.metadata();
352        if !self.accepts(meta) {
353            return;
354        }
355        let mut visitor = FieldVisitor::default();
356        event.record(&mut visitor);
357        let message = visitor
358            .fields
359            .iter()
360            .find(|(k, _)| k == "message")
361            .map(|(_, v)| v.clone());
362        let captured = CapturedEvent {
363            level: *meta.level(),
364            target: meta.target().to_owned(),
365            message,
366            fields: visitor.fields,
367        };
368        self.buffer
369            .lock()
370            .expect("log-tap buffer poisoned")
371            .push(captured);
372    }
373}
374
375#[derive(Default)]
376struct FieldVisitor {
377    fields: Vec<(String, String)>,
378}
379
380impl FieldVisitor {
381    fn push(&mut self, field: &Field, value: String) {
382        self.fields.push((field.name().to_string(), value));
383    }
384}
385
386impl Visit for FieldVisitor {
387    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
388        // `{:?}` on a &str yields quotes; strip them so `field = "x"` -> `x`.
389        let rendered = format!("{value:?}");
390        let cleaned = strip_debug_quotes(&rendered);
391        self.push(field, cleaned);
392    }
393
394    fn record_str(&mut self, field: &Field, value: &str) {
395        self.push(field, value.to_string());
396    }
397
398    fn record_i64(&mut self, field: &Field, value: i64) {
399        self.push(field, value.to_string());
400    }
401
402    fn record_u64(&mut self, field: &Field, value: u64) {
403        self.push(field, value.to_string());
404    }
405
406    fn record_i128(&mut self, field: &Field, value: i128) {
407        self.push(field, value.to_string());
408    }
409
410    fn record_u128(&mut self, field: &Field, value: u128) {
411        self.push(field, value.to_string());
412    }
413
414    fn record_bool(&mut self, field: &Field, value: bool) {
415        self.push(field, value.to_string());
416    }
417
418    fn record_f64(&mut self, field: &Field, value: f64) {
419        self.push(field, value.to_string());
420    }
421}
422
423fn strip_debug_quotes(s: &str) -> String {
424    if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
425        s[1..s.len() - 1].to_string()
426    } else {
427        s.to_string()
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    #[test]
436    fn captures_fields_and_asserts() {
437        let tap = LogTap::new().install();
438        tracing::info!(user_id = 7, action = "login", "hi");
439        tap.assert_contains(Level::INFO, "", &[("user_id", "7"), ("action", "login")]);
440        // message captured
441        let events = tap.events();
442        assert_eq!(events.len(), 1);
443        assert_eq!(events[0].message.as_deref(), Some("hi"));
444    }
445
446    #[test]
447    fn assert_not_contains_passes_when_absent() {
448        let tap = LogTap::new().install();
449        tracing::warn!(code = 500, "boom");
450        tap.assert_not_contains(Level::ERROR, "", &[]);
451        tap.assert_not_contains(Level::WARN, "", &[("code", "404")]);
452        tap.assert_contains(Level::WARN, "", &[("code", "500")]);
453    }
454
455    #[test]
456    fn level_filter_drops_lower_severity() {
457        let tap = LogTap::new().level(Level::WARN).install();
458        tracing::info!("ignored");
459        tracing::debug!("ignored too");
460        tracing::warn!(kept = true, "warn");
461        tracing::error!(kept = true, "err");
462        let events = tap.events();
463        assert_eq!(events.len(), 2);
464        assert!(events.iter().all(|e| e.level <= Level::WARN));
465    }
466
467    #[test]
468    fn target_prefix_filter() {
469        let tap = LogTap::new().target("tpt_log_tap").install();
470        tracing::info!(x = 1, "kept: this module's target starts with the prefix");
471        // A synthetic event with a different target is filtered.
472        assert!(tap.contains(Level::INFO, "", &[("x", "1")]));
473    }
474
475    #[test]
476    fn field_accessor_and_has_fields() {
477        let tap = LogTap::new().install();
478        tracing::info!(a = 1, b = "two", "msg");
479        let e = &tap.events()[0];
480        assert_eq!(e.field("a"), Some("1"));
481        assert_eq!(e.field("b"), Some("two"));
482        assert!(e.has_fields(&[("a", "1"), ("b", "two")]));
483        assert!(!e.has_fields(&[("a", "9")]));
484    }
485
486    #[test]
487    fn pending_expectation_met_does_not_panic() {
488        let mut tap = LogTap::new().install();
489        tap.expect_contains(Level::INFO, "", &[("done", "true")]);
490        tracing::info!(done = true, "finished");
491        drop(tap); // should not panic
492    }
493
494    #[test]
495    fn pending_expectation_unmet_panics_on_drop() {
496        let result = std::panic::catch_unwind(|| {
497            let mut tap = LogTap::new().install();
498            tap.expect_contains(Level::ERROR, "", &[("never", "logged")]);
499            tracing::info!("something else");
500            drop(tap);
501        });
502        assert!(result.is_err(), "unmet expectation should panic on drop");
503    }
504
505    #[test]
506    fn isolation_between_taps_on_same_thread() {
507        {
508            let first = LogTap::new().install();
509            tracing::info!(scope = "first", "a");
510            assert_eq!(first.len(), 1);
511        } // first uninstalled here
512        let second = LogTap::new().install();
513        tracing::info!(scope = "second", "b");
514        assert_eq!(second.len(), 1);
515        assert!(second.contains(Level::INFO, "", &[("scope", "second")]));
516        assert!(!second.contains(Level::INFO, "", &[("scope", "first")]));
517    }
518
519    #[test]
520    fn parallel_threads_are_isolated() {
521        use std::thread;
522        let handles: Vec<_> = (0..8)
523            .map(|i| {
524                thread::spawn(move || {
525                    let tap = LogTap::new().install();
526                    tracing::info!(thread = i, "work");
527                    // Each thread should see exactly its own single event.
528                    assert_eq!(tap.len(), 1, "thread {i} saw cross-talk");
529                    assert!(tap.contains(Level::INFO, "", &[("thread", &i.to_string())]));
530                })
531            })
532            .collect();
533        for h in handles {
534            h.join().unwrap();
535        }
536    }
537}