Skip to main content

rig_tap/
extract.rs

1//! Extraction helpers for decoding emitted observability events.
2
3use tracing::field::{Field, Visit};
4
5use crate::emit::EVENT_TARGET;
6use crate::event::ObservabilityEvent;
7
8struct EventVisitor {
9    json: Option<String>,
10}
11
12impl Visit for EventVisitor {
13    fn record_str(&mut self, field: &Field, value: &str) {
14        if field.name() == "event" {
15            self.json = Some(value.to_string());
16        }
17    }
18
19    fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
20        if field.name() == "event" && self.json.is_none() {
21            self.json = Some(format!("{value:?}"));
22        }
23    }
24}
25
26/// Extracts an [`ObservabilityEvent`] from a given tracing event, if the event
27/// belongs to the `rig_tap` target and is valid JSON.
28///
29/// This helper is intended for consumers who want to write their own custom
30/// `tracing_subscriber::Layer` without duplicating the extraction boilerplate.
31pub fn extract_event(event: &tracing::Event<'_>) -> Option<ObservabilityEvent> {
32    if event.metadata().target() != EVENT_TARGET {
33        return None;
34    }
35    let mut visitor = EventVisitor { json: None };
36    event.record(&mut visitor);
37    let json = visitor.json?;
38    serde_json::from_str(&json).ok()
39}