use std::sync::{Arc, Mutex};
use tracing::field::{Field, Visit};
use tracing::{Event, Metadata, Subscriber, span};
#[derive(Default, Clone)]
pub(crate) struct CapturedEvent {
pub(crate) fields: Vec<(String, String)>,
}
impl CapturedEvent {
pub(crate) fn field(&self, name: &str) -> Option<&str> {
self.fields
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.as_str())
}
}
pub(crate) fn captured_logs(f: impl FnOnce()) -> Vec<CapturedEvent> {
crate::scripting::keep_scoped_captures_visible();
let events = Arc::new(Mutex::new(Vec::new()));
let capture = TemplateLogCapture {
events: Arc::clone(&events),
};
tracing::subscriber::with_default(capture, f);
let collected = events.lock().expect("capture buffer");
collected.clone()
}
struct TemplateLogCapture {
events: Arc<Mutex<Vec<CapturedEvent>>>,
}
impl Subscriber for TemplateLogCapture {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.target() == "rift::template"
}
fn new_span(&self, _span: &span::Attributes<'_>) -> span::Id {
span::Id::from_u64(1)
}
fn record(&self, _span: &span::Id, _values: &span::Record<'_>) {}
fn record_follows_from(&self, _span: &span::Id, _follows: &span::Id) {}
fn event(&self, event: &Event<'_>) {
let mut captured = CapturedEvent::default();
event.record(&mut captured);
self.events.lock().expect("capture buffer").push(captured);
}
fn enter(&self, _span: &span::Id) {}
fn exit(&self, _span: &span::Id) {}
}
impl Visit for CapturedEvent {
fn record_str(&mut self, field: &Field, value: &str) {
self.fields
.push((field.name().to_string(), value.to_string()));
}
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
self.fields
.push((field.name().to_string(), format!("{value:?}")));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn template_warning(value: &str) {
tracing::warn!(target: "rift::template", value, "probe");
}
#[test]
fn a_callsite_another_thread_registered_first_is_still_captured() {
let events = captured_logs(|| {
std::thread::spawn(|| template_warning("elsewhere"))
.join()
.expect("thread");
template_warning("here");
});
assert_eq!(events.len(), 1, "only the capturing thread's event");
assert_eq!(events[0].field("value"), Some("here"));
}
}