Skip to main content

sentry_tracing/
converters.rs

1use std::collections::BTreeMap;
2use std::error::Error;
3
4use sentry_core::protocol::{Event, Exception, Mechanism, Value};
5#[cfg(feature = "logs")]
6use sentry_core::protocol::{Log, LogAttribute, LogLevel};
7use sentry_core::{event_from_error, Breadcrumb, Level, TransactionOrSpan};
8#[cfg(feature = "logs")]
9use std::time::SystemTime;
10use tracing_core::field::{Field, Visit};
11use tracing_core::Subscriber;
12use tracing_subscriber::layer::Context;
13use tracing_subscriber::registry::LookupSpan;
14
15use super::layer::SentrySpanData;
16use crate::TAGS_PREFIX;
17
18/// Converts a [`tracing_core::Level`] to a Sentry [`Level`], used for events and breadcrumbs.
19fn level_to_sentry_level(level: &tracing_core::Level) -> Level {
20    match *level {
21        tracing_core::Level::TRACE | tracing_core::Level::DEBUG => Level::Debug,
22        tracing_core::Level::INFO => Level::Info,
23        tracing_core::Level::WARN => Level::Warning,
24        tracing_core::Level::ERROR => Level::Error,
25    }
26}
27
28/// Converts a [`tracing_core::Level`] to a Sentry [`LogLevel`], used for logs.
29#[cfg(feature = "logs")]
30fn level_to_log_level(level: &tracing_core::Level) -> LogLevel {
31    match *level {
32        tracing_core::Level::TRACE => LogLevel::Trace,
33        tracing_core::Level::DEBUG => LogLevel::Debug,
34        tracing_core::Level::INFO => LogLevel::Info,
35        tracing_core::Level::WARN => LogLevel::Warn,
36        tracing_core::Level::ERROR => LogLevel::Error,
37    }
38}
39
40/// Converts a [`tracing_core::Level`] to the corresponding Sentry [`Exception::ty`] entry.
41#[cfg(feature = "backtrace")]
42fn level_to_exception_type(level: &tracing_core::Level) -> &'static str {
43    match *level {
44        tracing_core::Level::TRACE => "tracing::trace!",
45        tracing_core::Level::DEBUG => "tracing::debug!",
46        tracing_core::Level::INFO => "tracing::info!",
47        tracing_core::Level::WARN => "tracing::warn!",
48        tracing_core::Level::ERROR => "tracing::error!",
49    }
50}
51
52/// Extracts the message and metadata from an event.
53fn extract_event_data(
54    event: &tracing_core::Event,
55    store_errors_in_values: bool,
56) -> (Option<String>, FieldVisitor) {
57    // Find message of the event, if any
58    let mut visitor = FieldVisitor {
59        store_errors_in_values,
60        ..Default::default()
61    };
62    event.record(&mut visitor);
63    let message = visitor
64        .json_values
65        .remove("message")
66        // When #[instrument(err)] is used the event does not have a message attached to it.
67        // the error message is attached to the field "error".
68        .or_else(|| visitor.json_values.remove("error"))
69        .and_then(|v| match v {
70            Value::String(s) => Some(s),
71            _ => None,
72        });
73
74    (message, visitor)
75}
76
77/// Extracts the message and metadata from an event, including the data in the current span.
78fn extract_event_data_with_context<S>(
79    event: &tracing_core::Event,
80    ctx: Option<&Context<S>>,
81    store_errors_in_values: bool,
82) -> (Option<String>, FieldVisitor)
83where
84    S: Subscriber + for<'a> LookupSpan<'a>,
85{
86    let (message, mut visitor) = extract_event_data(event, store_errors_in_values);
87
88    // Add the context fields of every parent span.
89    let current_span = ctx.as_ref().and_then(|ctx| {
90        event
91            .parent()
92            .and_then(|id| ctx.span(id))
93            .or_else(|| ctx.lookup_current())
94    });
95    if let Some(span) = current_span {
96        for span in span.scope() {
97            let name = span.name();
98            let ext = span.extensions();
99
100            if let Some(span_data) = ext.get::<SentrySpanData>() {
101                match &span_data.sentry_span {
102                    TransactionOrSpan::Span(span) => {
103                        for (key, value) in span.data().iter() {
104                            if is_sentry_span_attribute(key) {
105                                continue;
106                            }
107                            if key != "message" {
108                                let key = format!("{name}:{key}");
109                                visitor.json_values.insert(key, value.clone());
110                            }
111                        }
112                    }
113                    TransactionOrSpan::Transaction(transaction) => {
114                        for (key, value) in transaction.data().iter() {
115                            if is_sentry_span_attribute(key) {
116                                continue;
117                            }
118                            if key != "message" {
119                                let key = format!("{name}:{key}");
120                                visitor.json_values.insert(key, value.clone());
121                            }
122                        }
123                    }
124                }
125            }
126        }
127    }
128
129    (message, visitor)
130}
131
132/// Checks whether the given attribute name is one of those set on a span by the Sentry layer.
133/// In that case, we want to skip materializing it when propagating attributes, as it would mostly create noise.
134fn is_sentry_span_attribute(name: &str) -> bool {
135    matches!(
136        name,
137        "sentry.tracing.target" | "code.module.name" | "code.file.path" | "code.line.number"
138    )
139}
140
141/// Records the fields of a [`tracing_core::Event`].
142#[derive(Default)]
143pub(crate) struct FieldVisitor {
144    pub(crate) json_values: BTreeMap<String, Value>,
145    pub(crate) exceptions: Vec<Exception>,
146    /// If `true`, stringify and store errors in `self.json_values` under the original field name
147    /// else (default), convert to `Exception`s and store in `self.exceptions`.
148    store_errors_in_values: bool,
149}
150
151impl FieldVisitor {
152    fn record<T: Into<Value>>(&mut self, field: &Field, value: T) {
153        self.json_values
154            .insert(field.name().to_owned(), value.into());
155    }
156}
157
158impl Visit for FieldVisitor {
159    fn record_i64(&mut self, field: &Field, value: i64) {
160        self.record(field, value);
161    }
162
163    fn record_u64(&mut self, field: &Field, value: u64) {
164        self.record(field, value);
165    }
166
167    fn record_bool(&mut self, field: &Field, value: bool) {
168        self.record(field, value);
169    }
170
171    fn record_f64(&mut self, field: &Field, value: f64) {
172        self.record(field, value);
173    }
174
175    fn record_str(&mut self, field: &Field, value: &str) {
176        self.record(field, value);
177    }
178
179    fn record_error(&mut self, field: &Field, value: &(dyn Error + 'static)) {
180        let event = event_from_error(value);
181        if self.store_errors_in_values {
182            let error_chain = event
183                .exception
184                .iter()
185                .rev()
186                .filter_map(|x| x.value.as_ref().map(|v| format!("{}: {}", x.ty, *v)))
187                .collect::<Vec<String>>();
188            self.record(field, error_chain);
189        } else {
190            for exception in event.exception {
191                self.exceptions.push(exception);
192            }
193        }
194    }
195
196    fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
197        self.record(field, format!("{value:?}"));
198    }
199}
200
201/// Creates a [`Breadcrumb`] from a given [`tracing_core::Event`].
202pub fn breadcrumb_from_event<'context, S>(
203    event: &tracing_core::Event,
204    ctx: impl Into<Option<&'context Context<'context, S>>>,
205) -> Breadcrumb
206where
207    S: Subscriber + for<'a> LookupSpan<'a>,
208{
209    let (message, visitor) = extract_event_data_with_context(event, ctx.into(), true);
210
211    Breadcrumb {
212        category: Some(event.metadata().target().to_owned()),
213        ty: "log".into(),
214        level: level_to_sentry_level(event.metadata().level()),
215        message,
216        data: visitor.json_values,
217        ..Default::default()
218    }
219}
220
221/// Convert `tracing` fields to the corresponding Sentry tags, removing them from `fields`.
222fn extract_and_remove_tags(fields: &mut BTreeMap<String, Value>) -> BTreeMap<String, String> {
223    let mut tags = BTreeMap::new();
224
225    fields.retain(|key, value| {
226        let Some(key) = key.strip_prefix(TAGS_PREFIX) else {
227            return true;
228        };
229        let string = match value {
230            Value::Bool(b) => b.to_string(),
231            Value::Number(n) => n.to_string(),
232            Value::String(s) => std::mem::take(s),
233            // remove null entries since empty tags are not allowed
234            Value::Null => return false,
235            // keep entries that cannot be represented as simple string
236            Value::Array(_) | Value::Object(_) => return true,
237        };
238
239        tags.insert(key.to_owned(), string);
240
241        false
242    });
243
244    tags
245}
246
247/// Create Sentry Contexts out of the `tracing` event and fields.
248fn contexts_from_event(
249    event: &tracing_core::Event,
250    fields: BTreeMap<String, Value>,
251) -> BTreeMap<String, sentry_core::protocol::Context> {
252    let event_meta = event.metadata();
253    let mut location_map = BTreeMap::new();
254    if let Some(module_path) = event_meta.module_path() {
255        location_map.insert("module_path".to_string(), module_path.into());
256    }
257    if let Some(file) = event_meta.file() {
258        location_map.insert("file".to_string(), file.into());
259    }
260    if let Some(line) = event_meta.line() {
261        location_map.insert("line".to_string(), line.into());
262    }
263
264    let mut context = BTreeMap::new();
265    if !fields.is_empty() {
266        context.insert(
267            "Rust Tracing Fields".to_string(),
268            sentry_core::protocol::Context::Other(fields),
269        );
270    }
271    if !location_map.is_empty() {
272        context.insert(
273            "Rust Tracing Location".to_string(),
274            sentry_core::protocol::Context::Other(location_map),
275        );
276    }
277    context
278}
279
280/// Creates an [`Event`] (possibly carrying exceptions) from a given [`tracing_core::Event`].
281pub fn event_from_event<'context, S>(
282    event: &tracing_core::Event,
283    ctx: impl Into<Option<&'context Context<'context, S>>>,
284) -> Event<'static>
285where
286    S: Subscriber + for<'a> LookupSpan<'a>,
287{
288    // Exception records in Sentry need a valid type, value and full stack trace to support
289    // proper grouping and issue metadata generation. tracing_core::Record does not contain sufficient
290    // information for this. However, it may contain a serialized error which we can parse to emit
291    // an exception record.
292    let (message, visitor) = extract_event_data_with_context(event, ctx.into(), false);
293    let FieldVisitor {
294        mut exceptions,
295        mut json_values,
296        store_errors_in_values: _,
297    } = visitor;
298
299    // If there are a message, an exception, and we are capturing stack traces, then add the message
300    // as synthetic wrapper around the exception to support proper grouping. The stack trace to
301    // attach is the current one, since it points to the place where the exception is captured.
302    // We should only do this if we're capturing stack traces, otherwise the issue title will be `<unknown>`
303    // as Sentry will attempt to use missing stack trace to determine the title.
304    #[cfg(feature = "backtrace")]
305    let message = {
306        let mut message = message;
307        if !exceptions.is_empty() && message.is_some() {
308            if let Some(client) = sentry_core::Hub::current().client() {
309                if client.options().attach_stacktrace {
310                    let thread = sentry_backtrace::current_thread(true);
311                    let exception = Exception {
312                        ty: level_to_exception_type(event.metadata().level()).to_owned(),
313                        value: message.take(),
314                        module: event.metadata().module_path().map(str::to_owned),
315                        stacktrace: thread.stacktrace,
316                        raw_stacktrace: thread.raw_stacktrace,
317                        thread_id: thread.id,
318                        mechanism: Some(Mechanism {
319                            synthetic: Some(true),
320                            ..Mechanism::default()
321                        }),
322                    };
323                    exceptions.push(exception)
324                }
325            }
326        }
327        message
328    };
329
330    if let Some(exception) = exceptions.last_mut() {
331        "tracing".clone_into(
332            &mut exception
333                .mechanism
334                .get_or_insert_with(Mechanism::default)
335                .ty,
336        );
337    }
338
339    Event {
340        logger: Some(event.metadata().target().to_owned()),
341        level: level_to_sentry_level(event.metadata().level()),
342        message,
343        exception: exceptions.into(),
344        tags: extract_and_remove_tags(&mut json_values),
345        contexts: contexts_from_event(event, json_values),
346        ..Default::default()
347    }
348}
349
350/// Creates a [`Log`] from a given [`tracing_core::Event`]
351#[cfg(feature = "logs")]
352pub fn log_from_event<'context, S>(
353    event: &tracing_core::Event,
354    ctx: impl Into<Option<&'context Context<'context, S>>>,
355) -> Log
356where
357    S: Subscriber + for<'a> LookupSpan<'a>,
358{
359    let (message, visitor) = extract_event_data_with_context(event, ctx.into(), true);
360
361    let mut attributes: BTreeMap<String, LogAttribute> = visitor
362        .json_values
363        .into_iter()
364        .map(|(key, val)| (key, val.into()))
365        .collect();
366
367    let event_meta = event.metadata();
368    if let Some(module_path) = event_meta.module_path() {
369        attributes.insert("code.module.name".to_owned(), module_path.into());
370    }
371    if let Some(file) = event_meta.file() {
372        attributes.insert("code.file.path".to_owned(), file.into());
373    }
374    if let Some(line) = event_meta.line() {
375        attributes.insert("code.line.number".to_owned(), line.into());
376    }
377
378    attributes.insert("sentry.origin".to_owned(), "auto.tracing".into());
379
380    Log {
381        level: level_to_log_level(event.metadata().level()),
382        body: message.unwrap_or_default(),
383        trace_id: None,
384        timestamp: SystemTime::now(),
385        severity_number: None,
386        attributes,
387    }
388}