minitrace/
event.rs

1// Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
2
3use std::borrow::Cow;
4
5use crate::local::local_span_stack::LOCAL_SPAN_STACK;
6use crate::Span;
7
8/// An event that represents a single point in time during the execution of a span.
9pub struct Event;
10
11impl Event {
12    /// Adds an event to the parent span with the given name and properties.
13    ///
14    /// # Examples
15    ///
16    /// ```
17    /// use minitrace::prelude::*;
18    ///
19    /// let root = Span::root("root", SpanContext::random());
20    ///
21    /// Event::add_to_parent("event in root", &root, || [("key".into(), "value".into())]);
22    /// ```
23    pub fn add_to_parent<I, F>(name: impl Into<Cow<'static, str>>, parent: &Span, properties: F)
24    where
25        I: IntoIterator<Item = (Cow<'static, str>, Cow<'static, str>)>,
26        F: FnOnce() -> I,
27    {
28        #[cfg(feature = "enable")]
29        {
30            let mut span = Span::enter_with_parent(name, parent).with_properties(properties);
31            if let Some(mut inner) = span.inner.take() {
32                inner.raw_span.is_event = true;
33                inner.submit_spans();
34            }
35        }
36    }
37
38    /// Adds an event to the current local parent span with the given name and properties.
39    ///
40    /// # Examples
41    ///
42    /// ```
43    /// use minitrace::prelude::*;
44    ///
45    /// let root = Span::root("root", SpanContext::random());
46    /// let _guard = root.set_local_parent();
47    ///
48    /// Event::add_to_local_parent("event in root", || [("key".into(), "value".into())]);
49    /// ```
50    pub fn add_to_local_parent<I, F>(name: impl Into<Cow<'static, str>>, properties: F)
51    where
52        I: IntoIterator<Item = (Cow<'static, str>, Cow<'static, str>)>,
53        F: FnOnce() -> I,
54    {
55        #[cfg(feature = "enable")]
56        {
57            LOCAL_SPAN_STACK
58                .try_with(|stack| stack.borrow_mut().add_event(name, properties))
59                .ok();
60        }
61    }
62}