Skip to main content

micromegas_telemetry_sink/
tracing_interop.rs

1use micromegas_tracing::{
2    dispatch::{
3        has_thread_stream, log_interop, log_interop_dyn_tagged, on_begin_async_named_scope_dyn,
4        on_end_async_named_scope_tagged,
5    },
6    levels::{LevelFilter, Verbosity},
7    logs::{FILTER_LEVEL_UNSET_VALUE, LogMetadata},
8    property_set::{DynProperty, PropertySet},
9    spans::SpanLocation,
10};
11use smallvec::SmallVec;
12use std::borrow::Cow;
13use std::cell::RefCell;
14use std::collections::HashMap;
15use std::ops::Range;
16use std::sync::{Mutex, OnceLock, atomic::AtomicU32};
17use tracing_subscriber::{layer::Context, prelude::*, registry::LookupSpan};
18
19use std::fmt::{self, Write};
20use tracing::field::{Field, Visit};
21
22const INLINE_FIELDS: usize = 4;
23
24/// Larger scratch buffers are dropped after the event instead of being kept for the thread's
25/// lifetime.
26const MAX_RETAINED_SCRATCH: usize = 4096;
27
28pub struct FieldFormatVisitor<'a> {
29    pub buffer: &'a mut String,
30    pub target: Option<String>,
31    /// Values of the event fields that become dynamic properties, concatenated.
32    pub values: &'a mut String,
33    /// Event fields that become dynamic properties, in addition to their message text, as
34    /// ranges into `values`.
35    pub properties: SmallVec<[(&'static str, Range<usize>); INLINE_FIELDS]>,
36}
37
38impl FieldFormatVisitor<'_> {
39    fn write_message_part(&mut self, field: &Field, value: &dyn fmt::Debug) {
40        if field.name() == "message" {
41            write!(self.buffer, "{value:?} ").expect("formatting into a String");
42        } else {
43            write!(self.buffer, "{}={:?} ", field.name(), value).expect("formatting into a String");
44        }
45    }
46
47    // `log.*` fields only carry the origin of a bridged `log` record.
48    fn is_property(field: &Field) -> bool {
49        field.name() != "message" && !field.name().starts_with("log.")
50    }
51}
52
53impl Visit for FieldFormatVisitor<'_> {
54    fn record_str(&mut self, field: &Field, value: &str) {
55        if field.name() == "log.target" {
56            self.target = Some(value.to_owned());
57            return;
58        }
59        if Self::is_property(field) {
60            let start = self.values.len();
61            self.values.push_str(value);
62            self.properties
63                .push((field.name(), start..self.values.len()));
64        }
65        self.write_message_part(field, &value);
66    }
67
68    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
69        if !Self::is_property(field) {
70            self.write_message_part(field, value);
71            return;
72        }
73        // Formatted once into `values`; the message reuses that text.
74        let start = self.values.len();
75        write!(self.values, "{value:?}").expect("formatting into a String");
76        let range = start..self.values.len();
77        self.buffer.push_str(field.name());
78        self.buffer.push('=');
79        self.buffer.push_str(&self.values[range.clone()]);
80        self.buffer.push(' ');
81        self.properties.push((field.name(), range));
82    }
83}
84
85#[derive(Default)]
86struct Scratch {
87    buffer: String,
88    values: String,
89}
90
91thread_local! {
92    // Reused across events so that capturing one does not allocate its working buffers.
93    static SCRATCH: RefCell<Scratch> = RefCell::default();
94}
95
96/// Decides what is stored for one span field value: `None` drops the field, `Some` keeps the
97/// returned value.
98///
99/// Arguments are the span's callsite metadata, the field name and the value as text (the `Debug`
100/// form for non-string values).
101pub type SpanFieldHook = Box<
102    dyn for<'v> Fn(&'static tracing::Metadata<'static>, &str, &'v str) -> Option<Cow<'v, str>>
103        + Send
104        + Sync,
105>;
106
107type SpanFieldHookRef<'a> = &'a (
108        dyn for<'v> Fn(&'static tracing::Metadata<'static>, &str, &'v str) -> Option<Cow<'v, str>>
109            + Send
110            + Sync
111    );
112
113/// A tracing layer compatible with `tracing_subscriber`.
114///
115/// Setting-up this layer still requires the proper initialization of a `TelemetryGuard`.
116pub struct TracingCaptureLayer {
117    pub max_level: LevelFilter,
118    /// Maps each `tracing` span to an async span, with its fields as end-event properties.
119    /// Only recorded when CPU tracing is enabled and on threads that have a Micromegas thread
120    /// stream (e.g. runtime threads or a thread holding a `TracingThreadGuard`); spans on other
121    /// threads are not recorded.
122    pub capture_spans: bool,
123    /// Called for each span field value before it is stored.
124    pub span_field_hook: Option<SpanFieldHook>,
125}
126
127/// Per-span state kept in the registry between `on_new_span` and `on_close`.
128struct CapturedSpan {
129    span_id: u64,
130    parent_span_id: u64,
131    depth: u32,
132    location: &'static SpanLocation,
133    fields: Vec<(&'static str, String)>,
134}
135
136/// Records span fields into owned storage, because they must outlive the callback that saw them.
137/// A `None` value means the hook dropped the field, which a later record must be able to express.
138struct SpanFieldVisitor<'a> {
139    metadata: &'static tracing::Metadata<'static>,
140    hook: Option<SpanFieldHookRef<'a>>,
141    fields: &'a mut Vec<(&'static str, Option<String>)>,
142}
143
144fn upsert<V>(fields: &mut Vec<(&'static str, V)>, name: &'static str, value: V) {
145    match fields.iter_mut().find(|(n, _)| *n == name) {
146        Some(entry) => entry.1 = value,
147        None => fields.push((name, value)),
148    }
149}
150
151/// Whether the hook returned its input untouched, so that it need not be copied again. The data
152/// pointer is compared as well as the length, because a same-length static replacement is not
153/// the input; an owned return never shares the input's address.
154fn is_whole_input(returned: &str, input: &str) -> bool {
155    std::ptr::eq(returned.as_ptr(), input.as_ptr()) && returned.len() == input.len()
156}
157
158impl Visit for SpanFieldVisitor<'_> {
159    fn record_str(&mut self, field: &Field, value: &str) {
160        if field.name().starts_with("log.") {
161            return;
162        }
163        let stored = match self.hook {
164            None => Some(value.to_owned()),
165            Some(hook) => hook(self.metadata, field.name(), value).map(Cow::into_owned),
166        };
167        upsert(self.fields, field.name(), stored);
168    }
169
170    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
171        if field.name().starts_with("log.") {
172            return;
173        }
174        let formatted = format!("{value:?}");
175        let stored = match self.hook {
176            None => Some(formatted),
177            Some(hook) => match hook(self.metadata, field.name(), &formatted) {
178                None => None,
179                Some(returned) if is_whole_input(&returned, &formatted) => {
180                    drop(returned);
181                    Some(formatted)
182                }
183                Some(returned) => Some(returned.into_owned()),
184            },
185        };
186        upsert(self.fields, field.name(), stored);
187    }
188}
189
190/// Span locations are keyed by address downstream, so each callsite needs one that never moves.
191fn span_location(metadata: &'static tracing::Metadata<'static>) -> &'static SpanLocation {
192    static LOCATIONS: OnceLock<Mutex<HashMap<usize, &'static SpanLocation>>> = OnceLock::new();
193    let mut locations = LOCATIONS
194        .get_or_init(Mutex::default)
195        .lock()
196        .unwrap_or_else(|poisoned| poisoned.into_inner());
197    // Leaked once per callsite, so the total is bounded by the program text.
198    locations
199        .entry(std::ptr::from_ref(metadata) as usize)
200        .or_insert_with(|| {
201            Box::leak(Box::new(SpanLocation {
202                lod: tracing_level_to_verbosity(metadata.level()),
203                target: metadata.target(),
204                module_path: metadata.module_path().unwrap_or_default(),
205                file: metadata.file().unwrap_or_default(),
206                line: metadata.line().unwrap_or(0),
207            }))
208        })
209}
210
211impl<S> tracing_subscriber::Layer<S> for TracingCaptureLayer
212where
213    S: tracing::Subscriber + for<'a> LookupSpan<'a>,
214{
215    fn on_new_span(
216        &self,
217        attrs: &tracing::span::Attributes<'_>,
218        id: &tracing::span::Id,
219        ctx: Context<'_, S>,
220    ) {
221        // A combined layer stack still creates spans that this layer's `enabled` rejected.
222        // The layer never creates a thread stream: one registered by a thread that then exits
223        // would be left dangling in the dispatch, so only threads that already own one record.
224        if !self.capture_spans
225            || !has_thread_stream()
226            || tracing_level_to_mm_level(attrs.metadata().level()) > self.max_level
227        {
228            return;
229        }
230        let Some(span) = ctx.span(id) else {
231            return;
232        };
233        let (parent_span_id, depth) = span
234            .scope()
235            .skip(1)
236            .find_map(|ancestor| {
237                ancestor
238                    .extensions()
239                    .get::<CapturedSpan>()
240                    .map(|parent| (parent.span_id, parent.depth + 1))
241            })
242            .unwrap_or((0, 0));
243        let location = span_location(span.metadata());
244        let name = span.name();
245        let mut recorded = vec![];
246        attrs.record(&mut SpanFieldVisitor {
247            metadata: attrs.metadata(),
248            hook: self.span_field_hook.as_deref(),
249            fields: &mut recorded,
250        });
251        let fields = recorded
252            .into_iter()
253            .filter_map(|(name, value)| value.map(|value| (name, value)))
254            .collect();
255        // The registry borrow is released before dispatching, since a sink may emit spans too.
256        drop(span);
257
258        let span_id = on_begin_async_named_scope_dyn(location, name, parent_span_id, depth);
259        if let Some(span) = ctx.span(id) {
260            span.extensions_mut().insert(CapturedSpan {
261                span_id,
262                parent_span_id,
263                depth,
264                location,
265                fields,
266            });
267        }
268    }
269
270    fn on_record(
271        &self,
272        id: &tracing::span::Id,
273        values: &tracing::span::Record<'_>,
274        ctx: Context<'_, S>,
275    ) {
276        let Some(span) = ctx.span(id) else {
277            return;
278        };
279        if span.extensions().get::<CapturedSpan>().is_none() {
280            return;
281        }
282        // Recorded without holding the extensions lock, because a `Debug` impl may create a
283        // span, whose `on_new_span` reads the extensions of its ancestors.
284        let mut recorded = vec![];
285        values.record(&mut SpanFieldVisitor {
286            metadata: span.metadata(),
287            hook: self.span_field_hook.as_deref(),
288            fields: &mut recorded,
289        });
290        let mut extensions = span.extensions_mut();
291        if let Some(captured) = extensions.get_mut::<CapturedSpan>() {
292            for (name, value) in recorded {
293                match value {
294                    Some(value) => upsert(&mut captured.fields, name, value),
295                    None => captured.fields.retain(|(n, _)| *n != name),
296                }
297            }
298        }
299    }
300
301    fn on_close(&self, id: tracing::span::Id, ctx: Context<'_, S>) {
302        let Some(span) = ctx.span(&id) else {
303            return;
304        };
305        let name = span.name();
306        let captured = span.extensions_mut().remove::<CapturedSpan>();
307        drop(span);
308        let Some(captured) = captured else {
309            return;
310        };
311        // A span dropped during thread-local teardown would panic (and abort) when the end
312        // event reaches the already-destroyed thread stream.
313        if !has_thread_stream() {
314            return;
315        }
316
317        let dyn_properties: SmallVec<[DynProperty<'_>; INLINE_FIELDS]> = captured
318            .fields
319            .iter()
320            .map(|(name, value)| DynProperty::new(name, value))
321            .collect();
322        on_end_async_named_scope_tagged(
323            captured.span_id,
324            captured.parent_span_id,
325            captured.location,
326            name,
327            captured.depth,
328            PropertySet::empty(),
329            &dyn_properties,
330        );
331    }
332
333    fn enabled(&self, metadata: &tracing::Metadata<'_>, _ctx: Context<'_, S>) -> bool {
334        let level = tracing_level_to_mm_level(metadata.level());
335        level <= self.max_level
336    }
337
338    fn on_event(
339        &self,
340        event: &tracing::Event<'_>,
341        _ctx: tracing_subscriber::layer::Context<'_, S>,
342    ) {
343        let level = tracing_level_to_mm_level(event.metadata().level());
344        if level > self.max_level {
345            return;
346        }
347        let capture = |scratch: &mut Scratch| capture_event(event, level, scratch);
348        // A sink that emits `tracing` events re-enters here while the scratch is borrowed, and
349        // thread-local destruction makes it unavailable; both fall back to fresh buffers.
350        let reused = SCRATCH
351            .try_with(|cell| match cell.try_borrow_mut() {
352                Ok(mut scratch) => {
353                    // The buffers keep the previous event's contents, which also covers a capture that panicked.
354                    scratch.buffer.clear();
355                    scratch.values.clear();
356                    capture(&mut scratch);
357                    if scratch.buffer.capacity() > MAX_RETAINED_SCRATCH
358                        || scratch.values.capacity() > MAX_RETAINED_SCRATCH
359                    {
360                        *scratch = Scratch::default();
361                    }
362                    true
363                }
364                Err(_) => false,
365            })
366            .unwrap_or(false);
367        if !reused {
368            capture(&mut Scratch::default());
369        }
370    }
371}
372
373fn capture_event(
374    event: &tracing::Event<'_>,
375    level: micromegas_tracing::levels::Level,
376    scratch: &mut Scratch,
377) {
378    let mut formatter = FieldFormatVisitor {
379        buffer: &mut scratch.buffer,
380        target: None,
381        values: &mut scratch.values,
382        properties: SmallVec::new(),
383    };
384    event.record(&mut formatter);
385    let FieldFormatVisitor {
386        buffer,
387        target,
388        values,
389        properties,
390    } = formatter;
391    let log_desc = LogMetadata {
392        level,
393        level_filter: AtomicU32::new(FILTER_LEVEL_UNSET_VALUE),
394        fmt_str: "{}",
395        target: target.as_deref().unwrap_or(event.metadata().target()),
396        module_path: event.metadata().module_path().unwrap_or_default(),
397        file: "",
398        line: 0,
399    };
400
401    if properties.is_empty() {
402        log_interop(&log_desc, format_args!("{buffer}"));
403    } else {
404        let dyn_properties: SmallVec<[DynProperty<'_>; INLINE_FIELDS]> = properties
405            .iter()
406            .map(|(name, range)| DynProperty::new(name, &values[range.clone()]))
407            .collect();
408        log_interop_dyn_tagged(&log_desc, &dyn_properties, format_args!("{buffer}"));
409    }
410}
411
412/// Installs a `tracing` layer that forwards events to the Micromegas tracing system.
413///
414/// This allows applications using the `tracing` crate to integrate with Micromegas telemetry.
415///
416/// # Arguments
417///
418/// * `interop_max_level_override` - An optional `LevelFilter` to override the maximum level
419///   for the `tracing` layer. If `None`, the global Micromegas max level is used.
420///
421/// `tracing` spans are recorded as async spans, but only when CPU tracing is enabled
422/// (`MICROMEGAS_ENABLE_CPU_TRACING`) and only on threads that have a Micromegas thread stream
423/// (e.g. runtime threads or a thread holding a `TracingThreadGuard`); spans on other threads are
424/// not recorded. Build a `TracingCaptureLayer` with `capture_spans: false` to forward events only.
425pub fn install_tracing_interop(interop_max_level_override: Option<LevelFilter>) {
426    let max_level = interop_max_level_override.unwrap_or(micromegas_tracing::levels::max_level());
427
428    tracing_subscriber::registry()
429        .with(TracingCaptureLayer {
430            max_level,
431            capture_spans: true,
432            span_field_hook: None,
433        })
434        .init();
435    tracing::debug!("installed tracing interop");
436}
437
438fn tracing_level_to_mm_level(level: &tracing_core::Level) -> micromegas_tracing::levels::Level {
439    match *level {
440        tracing_core::Level::ERROR => micromegas_tracing::levels::Level::Error,
441        tracing_core::Level::WARN => micromegas_tracing::levels::Level::Warn,
442        tracing_core::Level::INFO => micromegas_tracing::levels::Level::Info,
443        tracing_core::Level::DEBUG => micromegas_tracing::levels::Level::Debug,
444        tracing_core::Level::TRACE => micromegas_tracing::levels::Level::Trace,
445    }
446}
447
448fn tracing_level_to_verbosity(level: &tracing_core::Level) -> Verbosity {
449    match *level {
450        tracing_core::Level::ERROR | tracing_core::Level::WARN => Verbosity::Min,
451        tracing_core::Level::INFO => Verbosity::Med,
452        tracing_core::Level::DEBUG | tracing_core::Level::TRACE => Verbosity::Max,
453    }
454}