Something went wrong. Try again.
The format that's super! duper.dev.br
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022#![doc(html_logo_url = "https://duper.dev.br/logos/duper-100-100.png")]//! A composable [`tracing_subscriber`] layer to emit Duper events.//!//! You can install it to a [`tracing_subscriber::registry()`] just like any other//! filter or formatter://!//! ```//! use tracing_duper::DuperLayer;//! use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};//!//! tracing_subscriber::registry()//! // ... add filtering layers ...//! .with(DuperLayer::new().with_span_timings(true))//! .init();//! ```//!//! See [`DuperLayer`] for all the available configuration.//!//! Now, you can emit `tracing` spans and events as usual. If you'd like to//! emit Duper values, use `$duper.` as the prefix of the field, and set the//! value to a Duper-formatted string.//!//! ```//! use tracing::{debug, warn};//!//! #[tracing::instrument]//! fn send_gifts(count: &mut usize) {//! if *count < 12 {//! warn!("too few gifts... try again later");//! } else {//! debug!(//! user_id = &b"santa"[..],//! "$duper.delivery_date" = "(PlainMonthDay('12-25'), \"Christmas\")",//! "sending {count} gifts"//! );//! std::thread::sleep(std::time::Duration::from_millis(100));//! *count = 0;//! }//! }//! ```//!//! This should print logs like the following to stdout://!//! ```text//! {level:"WARN",timestamp:Instant('2025-12-04T13:29:33.947380870-03:00'),target:"simple",span:{count:10,span_id:1},spans:[{count:10,span_id:1}],fields:{message:"too few gifts... try again later"}}//! {level:"INFO",timestamp:Instant('2025-12-04T13:29:33.947608295-03:00'),target:"simple",span:{count:10,span_id:1},spans:[{count:10,span_id:1}],fields:{span_event:"closed","span_time.busy":Duration('PT0.000265196S'),"span_time.idle":Duration('PT0.000003567S')}}//! {level:"DEBUG",timestamp:Instant('2025-12-04T13:29:33.948805983-03:00'),target:"simple",span:{count:23,span_id:2251799813685249},spans:[{count:23,span_id:2251799813685249}],fields:{delivery_date:(PlainMonthDay('12-25'),"Christmas"),message:"sending 23 gifts",user_id:b"santa"}}//! {level:"INFO",timestamp:Instant('2025-12-04T13:29:34.049418692-03:00'),target:"simple",span:{count:23,span_id:2251799813685249},spans:[{count:23,span_id:2251799813685249}],fields:{span_event:"closed","span_time.busy":Duration('PT0.100555973S'),"span_time.idle":Duration('PT0.000001603S')}}//! ```//!//! To create Duper values programmatically, look into [`duper`] and [`duper::Serializer`], or//! the `serde_duper` crate.//!//! ## Feature flags//!//! - `chrono`: Use [`chrono`] to format log timestamps. Enabled by default.//!
use std::{ borrow::Cow, io::{self, Write}, marker::PhantomData, time::Instant,};
use duper::{DuperFloat, DuperIdentifier, DuperKey, DuperObject, DuperValue, Serializer};use indexmap::IndexMap;#[cfg(feature = "jiff")]use jiff::{Timestamp, Zoned};use tracing_core::{Event, Subscriber, field};use tracing_subscriber::{Layer, field::VisitOutput, registry::LookupSpan};
/// A trait to allow implementing timestamp generators.pub trait DuperTimer { /// Returns the current timestamp as a Duper value, or `None` if one cannot /// be generated. fn get_timestamp(&self) -> Option<DuperValue<'static>>;}
impl DuperTimer for () { fn get_timestamp(&self) -> Option<DuperValue<'static>> { None }}
#[cfg(feature = "jiff")]/// An Instant timestamp generator that uses [`jiff`] and includes the UTC timezone.pub struct JiffTimestampTimer;
#[cfg(feature = "jiff")]impl DuperTimer for JiffTimestampTimer { fn get_timestamp(&self) -> Option<DuperValue<'static>> { Some( DuperValue::try_instant_from(Cow::Owned(Timestamp::now().to_string())) .expect("valid ISO-8601 Instant"), ) }}
#[cfg(feature = "jiff")]/// An Instant timestamp generator that uses [`jiff`] and includes the local timezone.pub struct JiffZonedTimer;
#[cfg(feature = "jiff")]impl DuperTimer for JiffZonedTimer { fn get_timestamp(&self) -> Option<DuperValue<'static>> { Some( DuperValue::try_zoned_date_time_from(Cow::Owned(Zoned::now().to_string())) .expect("valid RFC-9557 ZonedDateTime"), ) }}
#[cfg(feature = "jiff")]/// A [`tracing_subscriber::Layer`] that generates Duper-formatted logs to the/// specified writer.////// By default, logs will be written to stdout, using [`JiffTimestampTimer`] as/// the timestamp generator.pub struct DuperLayer<S, W = fn() -> io::Stdout, Timer = JiffTimestampTimer> { make_writer: W, timer: Timer, flatten_event: bool, display_timestamp: bool, display_level: bool, display_target: bool, display_file: bool, display_line: bool, display_span_timings: bool, display_current_span: bool, display_span_list: bool, _subscriber: PhantomData<S>,}
#[cfg(not(feature = "jiff"))]/// A [`tracing_subscriber::Layer`] that generates Duper-formatted logs to the/// specified writer.////// By default, logs will be written to stdout, with no timestamp generator.pub struct DuperLayer<S, W = fn() -> io::Stdout, Timer = ()> { make_writer: W, timer: Timer, flatten_event: bool, display_timestamp: bool, display_level: bool, display_target: bool, display_file: bool, display_line: bool, display_span_timings: bool, display_current_span: bool, display_span_list: bool, _subscriber: PhantomData<S>,}
impl<S> Default for DuperLayer<S> { fn default() -> Self { #[cfg(feature = "jiff")] { Self { make_writer: io::stdout, timer: JiffTimestampTimer, flatten_event: false, display_timestamp: true, display_level: true, display_target: true, display_file: false, display_line: false, display_span_timings: false, display_current_span: true, display_span_list: true, _subscriber: Default::default(), } } #[cfg(not(feature = "jiff"))] { Self { make_writer: io::stdout, timer: (), flatten_event: false, display_timestamp: true, display_level: true, display_target: true, display_file: false, display_line: false, display_span_timings: false, display_current_span: true, display_span_list: true, _subscriber: Default::default(), } } }}
impl<S> DuperLayer<S> { /// Creates a new Duper layer with the default settings. pub fn new() -> Self { Self::default() }}
impl<S, W, Timer> DuperLayer<S, W, Timer> { /// Sets the timer to use with this layer. pub fn with_timer<Timer2>(self, timer: Timer2) -> DuperLayer<S, W, Timer2> { DuperLayer { timer, make_writer: self.make_writer, flatten_event: self.flatten_event, display_timestamp: self.display_timestamp, display_level: self.display_level, display_target: self.display_target, display_file: self.display_file, display_line: self.display_line, display_span_timings: self.display_span_timings, display_current_span: self.display_current_span, display_span_list: self.display_span_list, _subscriber: Default::default(), } }
/// Clear the timer from this layer, consequently disabling timestamps. pub fn without_timer(self) -> DuperLayer<S, W, ()> { DuperLayer { timer: (), make_writer: self.make_writer, flatten_event: self.flatten_event, display_timestamp: self.display_timestamp, display_level: self.display_level, display_target: self.display_target, display_file: self.display_file, display_line: self.display_line, display_span_timings: self.display_span_timings, display_current_span: self.display_current_span, display_span_list: self.display_span_list, _subscriber: Default::default(), } }
/// Sets the writer factory function to use with this layer. pub fn with_writer<W2>(self, make_writer: W2) -> DuperLayer<S, W2, Timer> { DuperLayer { make_writer, timer: self.timer, flatten_event: self.flatten_event, display_timestamp: self.display_timestamp, display_level: self.display_level, display_target: self.display_target, display_file: self.display_file, display_line: self.display_line, display_span_timings: self.display_span_timings, display_current_span: self.display_current_span, display_span_list: self.display_span_list, _subscriber: Default::default(), } }
/// Sets whether event fields will be flattened into the top-level of the /// log. /// /// NOTE: Keys that collide with existing ones will be discarded. pub fn flatten_event(self, flatten_event: bool) -> Self { Self { flatten_event, ..self } }
/// Sets whether timestamps will be displayed in logs or not. pub fn with_timestamp(self, display_timestamp: bool) -> Self { Self { display_timestamp, ..self } }
/// Sets whether log levels will be displayed in logs or not. pub fn with_level(self, display_level: bool) -> Self { Self { display_level, ..self } }
/// Sets whether the target (i.e. the source of the trace) will be displayed /// in logs or not. pub fn with_target(self, display_target: bool) -> Self { Self { display_target, ..self } }
/// Sets whether the file of the trace will be displayed in logs or not. pub fn with_file(self, display_file: bool) -> Self { Self { display_file, ..self } }
/// Sets whether the line number of the trace will be displayed in logs or /// not. pub fn with_line(self, display_line: bool) -> Self { Self { display_line, ..self } }
/// Sets whether the span timings will be displayed in logs or not. /// /// This has no effect if `display_current_span` and `display_span_list` are /// both unset. pub fn with_span_timings(self, display_span_timings: bool) -> Self { Self { display_span_timings, ..self } }
/// Sets whether the current span will be displayed in logs or not. pub fn with_current_span(self, display_current_span: bool) -> Self { Self { display_current_span, ..self } }
/// Sets whether the complete span list (current span, then each parent /// span) will be displayed in logs or not. pub fn with_span_list(self, display_span_list: bool) -> Self { Self { display_span_list, ..self } }
/// Sets whether timings for this span (busy, idle) should be tracked. If /// set to true, an event will be emitted when the span is closed. fn track_timings(&self) -> bool { self.display_span_timings && (self.display_current_span || self.display_span_list) }}
impl<S, W, Timer> Layer<S> for DuperLayer<S, W, Timer>where S: Subscriber + for<'span> LookupSpan<'span>, W: for<'writer> tracing_subscriber::fmt::writer::MakeWriter<'writer> + 'static, Timer: DuperTimer + 'static,{ fn on_new_span( &self, attrs: &tracing_core::span::Attributes<'_>, id: &tracing_core::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>, ) { let span = ctx.span(id).expect("span should exist"); let mut extensions = span.extensions_mut();
let mut visitor = DuperVisitor::new(); visitor.values.insert( DuperKey::from("span_id"), DuperValue::Integer { identifier: None, inner: id.into_u64() as i64, }, ); attrs.record(&mut visitor); let fields = visitor.finish(); extensions.insert(DuperFields(fields));
if self.track_timings() { extensions.insert(Timings::new()); drop(extensions); let metadata = span.metadata(); let callsite = metadata.callsite(); let field_set = field::FieldSet::new(&["span_event"], callsite); let mut fields = field_set.iter(); let values = [( &fields.next().unwrap(), Some(&"opened" as &dyn field::Value), )]; let value_set = field_set.value_set(&values); let event = Event::new_child_of(id, metadata, &value_set); self.on_event(&event, ctx.clone()); } }
fn on_record( &self, id: &tracing_core::span::Id, values: &tracing_core::span::Record<'_>, ctx: tracing_subscriber::layer::Context<'_, S>, ) { let span = ctx.span(id).expect("span should exist"); let mut extensions = span.extensions_mut(); if let Some(object) = extensions.get_mut::<DuperFields>() { let mut visitor = DuperVisitor::from_object(std::mem::replace( &mut object.0, DuperObject::try_from(vec![]).expect("empty object is valid"), )); values.record(&mut visitor); *object = DuperFields(visitor.finish()); return; }
let mut visitor = DuperVisitor::new(); values.record(&mut visitor); let fields = visitor.finish(); extensions.insert(DuperFields(fields)); }
fn on_event(&self, event: &Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) { let mut log = vec![]; let metadata = event.metadata();
if self.display_level { log.push(( DuperKey::from("level"), DuperValue::String { identifier: None, inner: Cow::Borrowed(metadata.level().as_str()), }, )); }
if self.display_timestamp && let Some(timestamp) = self.timer.get_timestamp() { log.push((DuperKey::from("timestamp"), timestamp)); }
if self.display_target { log.push(( DuperKey::from("target"), DuperValue::String { identifier: None, inner: Cow::Borrowed(metadata.target()), }, )); }
if self.display_file { log.push(( DuperKey::from("file"), metadata .file() .map(|file| DuperValue::String { identifier: None, inner: Cow::Borrowed(file), }) .unwrap_or(DuperValue::Null { identifier: None }), )); }
if self.display_line { log.push(( DuperKey::from("line"), metadata .line() .map(|line| DuperValue::Integer { identifier: None, inner: line.into(), }) .unwrap_or(DuperValue::Null { identifier: None }), )); }
if self.display_current_span || self.display_span_list { let current_span = event .parent() .and_then(|id| ctx.span(id)) .or_else(|| ctx.lookup_current()); if let Some(ref span) = current_span { let extensions = span.extensions(); if self.display_current_span && let Some(fields) = extensions.get::<DuperFields>() { log.push(( DuperKey::from("span"), DuperValue::Object { identifier: None, inner: fields.0.clone(), }, )); } if self.display_span_list { let mut spans = vec![]; if let Some(scope) = ctx.event_scope(event) { for span in scope.from_root() { let extensions = span.extensions(); if let Some(fields) = extensions.get::<DuperFields>() { spans.push(DuperValue::Object { identifier: None, inner: fields.0.clone(), }); } } } log.push(( DuperKey::from("spans"), DuperValue::Array { identifier: None, inner: spans, }, )); } } }
let mut fields_visitor = DuperVisitor::new(); event.record(&mut fields_visitor); let object = fields_visitor.finish(); if self.flatten_event { log.extend(object.into_inner()); } else { log.push(( DuperKey::from("fields"), DuperValue::Object { identifier: None, inner: object, }, )); }
let mut serializer = Serializer::new(false, true); if let Err(error) = writeln!( self.make_writer.make_writer_for(event.metadata()), "{}", serializer.serialize(&DuperValue::Object { identifier: None, inner: DuperObject::from_lossy(log), }) ) { let _ = error; } }
fn on_enter( &self, id: &tracing_core::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>, ) { if self.track_timings() { let span = ctx.span(id).expect("span should exist"); if let Some(timings) = span.extensions_mut().get_mut::<Timings>() { if timings.entered_count == 0 { let now = Instant::now(); timings.idle += (now - timings.last).as_nanos() as i64; timings.last = now; } timings.entered_count += 1; } } }
fn on_exit(&self, id: &tracing_core::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) { if self.track_timings() { let span = ctx.span(id).expect("span should exist"); if let Some(timings) = span.extensions_mut().get_mut::<Timings>() { timings.entered_count -= 1; if timings.entered_count == 0 { let now = Instant::now(); timings.busy += (now - timings.last).as_nanos() as i64; timings.last = now; } } } }
fn on_close(&self, id: tracing_core::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) { if self.track_timings() { let span = ctx.span(&id).expect("span should exist"); let mut extensions = span.extensions_mut(); if let Some(timings) = extensions.remove::<Timings>() { let metadata = span.metadata(); let callsite = metadata.callsite(); let field_set = field::FieldSet::new( &[ "span_event", "$duper.span_time.busy", "$duper.span_time.idle", ], callsite, ); let mut fields = field_set.iter(); let busy_duration = format!( "Duration('PT{}.{:09}S')", timings.busy / 1_000_000_000, timings.busy % 1_000_000_000 ); let idle_duration = format!( "Duration('PT{}.{:09}S')", timings.idle / 1_000_000_000, timings.idle % 1_000_000_000 ); let values = [ ( &fields.next().unwrap(), Some(&"closed" as &dyn field::Value), ), ( &fields.next().unwrap(), Some(&busy_duration as &dyn field::Value), ), ( &fields.next().unwrap(), Some(&idle_duration as &dyn field::Value), ), ]; let value_set = field_set.value_set(&values); let event = Event::new_child_of(id, metadata, &value_set); drop(extensions); drop(span); self.on_event(&event, ctx); } } }}
struct DuperFields<'a>(DuperObject<'a>);
struct DuperVisitor<'a> { values: IndexMap<DuperKey<'a>, DuperValue<'a>>, overwrite: bool,}
impl<'a> DuperVisitor<'a> { fn new() -> Self { Self { values: IndexMap::new(), overwrite: false, } }
/// Creates a visitor seeded with the given object's values, in overwrite /// mode so that recorded values replace existing ones (used by `on_record`, /// which updates span fields rather than recording them for the first time). fn from_object(object: DuperObject<'a>) -> Self { Self { values: object.into_inner(), overwrite: true, } }}
impl std::fmt::Debug for DuperVisitor<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("DuperVisitor") .field("values", &self.values) .finish() }}
impl<'a> tracing_subscriber::field::VisitOutput<DuperObject<'a>> for DuperVisitor<'a> { fn finish(self) -> DuperObject<'a> { DuperObject::from(self.values) }}
impl tracing_core::field::Visit for DuperVisitor<'_> { fn record_debug(&mut self, field: &tracing_core::Field, value: &dyn core::fmt::Debug) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; } self.values.insert( key, DuperValue::String { identifier: None, inner: Cow::Owned(format!("{:?}", value)), }, ); }
fn record_f64(&mut self, field: &tracing_core::Field, value: f64) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; } if let Ok(value) = DuperFloat::try_new(value) { self.values.insert( key, DuperValue::Float { identifier: None, inner: value, }, ); } }
fn record_i64(&mut self, field: &tracing_core::Field, value: i64) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; } self.values.insert( key, DuperValue::Integer { identifier: None, inner: value, }, ); }
fn record_u64(&mut self, field: &tracing_core::Field, value: u64) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; } if let Ok(value) = i64::try_from(value) { self.values.insert( key, DuperValue::Integer { identifier: None, inner: value, }, ); } else { self.values.insert( key, DuperValue::String { identifier: Some(DuperIdentifier::try_from("U64").expect("valid identifier")), inner: Cow::Owned(value.to_string()), }, ); } }
fn record_i128(&mut self, field: &tracing_core::Field, value: i128) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; } if let Ok(value) = i64::try_from(value) { self.values.insert( key, DuperValue::Integer { identifier: None, inner: value, }, ); } else { self.values.insert( key, DuperValue::String { identifier: Some(DuperIdentifier::try_from("I128").expect("valid identifier")), inner: Cow::Owned(value.to_string()), }, ); } }
fn record_u128(&mut self, field: &tracing_core::Field, value: u128) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; }
if let Ok(value) = i64::try_from(value) { self.values.insert( key, DuperValue::Integer { identifier: None, inner: value, }, ); } else { self.values.insert( key, DuperValue::String { identifier: Some(DuperIdentifier::try_from("U128").expect("valid identifier")), inner: Cow::Owned(value.to_string()), }, ); } }
fn record_bool(&mut self, field: &tracing_core::Field, value: bool) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; } self.values.insert( key, DuperValue::Boolean { identifier: None, inner: value, }, ); }
fn record_str(&mut self, field: &tracing_core::Field, value: &str) { let key = field.name(); if let Some(suffix) = key.strip_prefix("$duper.") && let Ok(value) = duper::DuperParser::parse_duper_value(value) { let key = DuperKey::from(suffix); if !self.overwrite && self.values.contains_key(&key) { return; } self.values.insert(key, value.static_clone()); } else { let key = DuperKey::from(key); if !self.overwrite && self.values.contains_key(&key) { return; } self.values.insert( key, DuperValue::String { identifier: None, inner: Cow::Owned(value.to_string()), }, ); } }
fn record_bytes(&mut self, field: &tracing_core::Field, value: &[u8]) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; } self.values.insert( key, DuperValue::Bytes { identifier: None, inner: Cow::Owned(value.to_vec()), }, ); }
fn record_error( &mut self, field: &tracing_core::Field, value: &(dyn std::error::Error + 'static), ) { let key = DuperKey::from(field.name()); if !self.overwrite && self.values.contains_key(&key) { return; } self.values.insert( key, DuperValue::String { identifier: Some(DuperIdentifier::try_from("Error").expect("valid identifier")), inner: Cow::Owned(value.to_string()), }, ); }}
struct Timings { idle: i64, busy: i64, last: Instant, entered_count: u64,}
impl Timings { fn new() -> Self { Self { idle: 0, busy: 0, last: Instant::now(), entered_count: 0, } }}
#[cfg(test)]mod tests { use super::*; use std::sync::{Arc, Mutex, MutexGuard}; use tracing_subscriber::{fmt::writer::MakeWriter, layer::SubscriberExt};
#[derive(Clone)] struct Buf(Arc<Mutex<Vec<u8>>>);
struct Guard<'a>(MutexGuard<'a, Vec<u8>>);
impl std::io::Write for Guard<'_> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> std::io::Result<()> { self.0.flush() } }
impl<'writer> MakeWriter<'writer> for Buf { type Writer = Guard<'writer>; fn make_writer(&'writer self) -> Self::Writer { Guard(self.0.lock().unwrap()) } }
fn run_with_buffer<F: FnOnce()>(run: F) -> String { let buf = Buf(Arc::default()); let layer = DuperLayer::new() .with_writer(buf.clone()) .without_timer() .with_level(false) .with_target(false) .with_span_timings(true); run_with_layer(&buf, layer, run) }
fn run_with_layer<F: FnOnce()>( buf: &Buf, layer: DuperLayer<tracing_subscriber::registry::Registry, Buf, ()>, run: F, ) -> String { let subscriber = tracing_subscriber::registry().with(layer); tracing::subscriber::with_default(subscriber, run); String::from_utf8(buf.0.lock().unwrap().clone()).expect("valid UTF-8 output") }
#[test] fn on_record_updates_duper_field() { let output = run_with_buffer(|| { let span = tracing::info_span!("my_span", "$duper.count" = "1"); span.record("$duper.count", "2"); let _guard = span.enter(); tracing::info!("hello"); });
assert!( output.contains(r#"span_event:"opened""#), "expected to enter `my_span`, got: {output}" ); assert!( output.contains("count:2"), "expected updated `$duper.count` value, got: {output}" ); assert!( output.contains(r#"span_event:"closed""#), "expected to close `my_span`, got: {output}" ); }
#[test] fn on_record_updates_plain_field() { let output = run_with_buffer(|| { let span = tracing::info_span!("my_span", "status" = "pending"); span.record("status", "done"); let _guard = span.enter(); tracing::info!("hello"); });
assert!( output.contains(r#"span_event:"opened""#), "expected to enter `my_span`, got: {output}" ); assert!( output.contains("status:\"done\""), "expected updated `status` value, got: {output}" ); assert!( output.contains(r#"span_event:"closed""#), "expected to close `my_span`, got: {output}" ); }
#[test] fn event_duper_field_is_parsed() { let output = run_with_buffer(|| { tracing::info!("$duper.count" = "2", "hello"); });
assert!( output.contains("count:2"), "expected parsed `$duper.count` value, got: {output}" ); assert!( !output.contains("$duper.count"), "expected `$duper.` prefix to be stripped, got: {output}" ); }
#[test] fn event_duper_field_complex_value() { let output = run_with_buffer(|| { tracing::info!("$duper.point" = "(1, 2)", "hello"); });
assert!( output.contains("point:(1,2)"), "expected parsed `$duper.point` tuple, got: {output}" ); }
#[test] fn event_plain_field_is_string() { let output = run_with_buffer(|| { tracing::info!("status" = "pending", "hello"); });
assert!( output.contains("status:\"pending\""), "expected plain field as a string, got: {output}" ); }
#[test] fn event_fields_flattened() { let buf = Buf(Arc::default()); let layer = DuperLayer::new() .with_writer(buf.clone()) .without_timer() .with_level(false) .with_target(false) .flatten_event(true);
let output = run_with_layer(&buf, layer, || { tracing::info!("status" = "pending", "hello"); });
assert!( output.contains("status:\"pending\"") && !output.contains("fields:"), "expected flattened event fields, got: {output}" ); }}