use std::sync::{Arc, Mutex, PoisonError};
use tracing::field::{Field, Visit};
use tracing::subscriber::DefaultGuard;
use tracing::{Event, Level, Subscriber};
use tracing_subscriber::layer::{Context, SubscriberExt};
use tracing_subscriber::{Layer, registry};
#[derive(Clone)]
struct Record {
level: Level,
message: String,
fields: Vec<String>,
}
#[derive(Clone, Default)]
pub(crate) struct LogCapture {
records: Arc<Mutex<Vec<Record>>>,
}
impl LogCapture {
pub(crate) fn messages(&self, level: Level) -> Vec<String> {
self.lock()
.iter()
.filter(|record| record.level == level)
.map(|record| record.message.clone())
.collect()
}
pub(crate) fn count(&self, level: Level, needle: &str) -> usize {
self.lock()
.iter()
.filter(|record| record.level == level && record.message.contains(needle))
.count()
}
pub(crate) fn mentions(&self, needle: &str) -> bool {
self.lock().iter().any(|record| {
record.message.contains(needle)
|| record.fields.iter().any(|field| field.contains(needle))
})
}
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Record>> {
self.records.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[derive(Default)]
struct FieldVisitor {
message: String,
fields: Vec<String>,
}
impl Visit for FieldVisitor {
fn record_str(&mut self, field: &Field, value: &str) {
if field.name() == "message" {
value.clone_into(&mut self.message);
} else {
self.fields.push(format!("{}={value}", field.name()));
}
}
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
if field.name() == "message" {
self.message = format!("{value:?}");
} else {
self.fields.push(format!("{}={value:?}", field.name()));
}
}
}
struct CaptureLayer {
records: Arc<Mutex<Vec<Record>>>,
}
impl<S: Subscriber> Layer<S> for CaptureLayer {
fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
let mut visitor = FieldVisitor::default();
event.record(&mut visitor);
self.records
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(Record {
level: *event.metadata().level(),
message: visitor.message,
fields: visitor.fields,
});
}
}
pub(crate) fn register_anchor_dispatcher() {
static ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
ANCHOR.get_or_init(|| tracing::Dispatch::new(registry()));
}
pub(crate) fn capture_logs() -> (DefaultGuard, LogCapture) {
register_anchor_dispatcher();
let capture = LogCapture::default();
let subscriber = registry().with(CaptureLayer {
records: Arc::clone(&capture.records),
});
(tracing::subscriber::set_default(subscriber), capture)
}
#[cfg(test)]
mod tests {
use tracing::Level;
use super::capture_logs;
#[test]
fn mentions_sees_structured_fields_of_every_kind() {
let (_guard, logs) = capture_logs();
let cause = std::io::Error::other("field_cause");
tracing::warn!(token = "str_field_secret", "plain message");
tracing::warn!(path = ?"debug_field_secret", "plain message");
tracing::warn!(error = %cause, "plain message");
tracing::warn!(bytes = 4242_u64, "plain message");
for needle in [
"str_field_secret",
"debug_field_secret",
"field_cause",
"4242",
] {
assert!(logs.mentions(needle), "{needle} is in a field");
}
assert_eq!(logs.count(Level::WARN, "plain message"), 4);
assert!(
logs.messages(Level::WARN)
.iter()
.all(|message| message == "plain message"),
"messages() carries the message only"
);
}
}