πŸ›ˆ Note: This is pre-release documentation for the upcoming tracing 0.2.0 ecosystem.

For the release documentation, please see docs.rs, instead.

tracing/
span.rs

1//! Spans represent periods of time in which a program was executing in a
2//! particular context.
3//!
4//! A span consists of [fields], user-defined key-value pairs of arbitrary data
5//! that describe the context the span represents, and a set of fixed attributes
6//! that describe all `tracing` spans and events. Attributes describing spans
7//! include:
8//!
9//! - An [`Id`] assigned by the subscriber that uniquely identifies it in relation
10//!   to other spans.
11//! - The span's [parent] in the trace tree.
12//! - [Metadata] that describes static characteristics of all spans
13//!   originating from that callsite, such as its name, source code location,
14//!   [verbosity level], and the names of its fields.
15//!
16//! # Creating Spans
17//!
18//! Spans are created using the [`span!`] macro. This macro is invoked with the
19//! following arguments, in order:
20//!
21//! - The [`target`] and/or [`parent`][parent] attributes, if the user wishes to
22//!   override their default values.
23//! - The span's [verbosity level]
24//! - A string literal providing the span's name.
25//! - Finally, zero or more arbitrary key/value fields.
26//!
27//! [`target`]: super::Metadata::target()
28//!
29//! For example:
30//! ```rust
31//! use tracing::{span, Level};
32//!
33//! /// Construct a new span at the `INFO` level named "my_span", with a single
34//! /// field named answer , with the value `42`.
35//! let my_span = span!(Level::INFO, "my_span", answer = 42);
36//! ```
37//!
38//! The documentation for the [`span!`] macro provides additional examples of
39//! the various options that exist when creating spans.
40//!
41//! The [`trace_span!`], [`debug_span!`], [`info_span!`], [`warn_span!`], and
42//! [`error_span!`] exist as shorthand for constructing spans at various
43//! verbosity levels.
44//!
45//! ## Recording Span Creation
46//!
47//! The [`Attributes`] type contains data associated with a span, and is
48//! provided to the [collector] when a new span is created. It contains
49//! the span's metadata, the ID of [the span's parent][parent] if one was
50//! explicitly set, and any fields whose values were recorded when the span was
51//! constructed. The collector, which is responsible for recording `tracing`
52//! data, can then store or record these values.
53//!
54//! # The Span Lifecycle
55//!
56//! ## Entering a Span
57//!
58//! A thread of execution is said to _enter_ a span when it begins executing,
59//! and _exit_ the span when it switches to another context. Spans may be
60//! entered through the [`enter`] and [`in_scope`] methods.
61//!
62//! The `enter` method enters a span, returning a [guard] that exits the span
63//! when dropped
64//! ```
65//! # use tracing::{Level, span};
66//! let my_var: u64 = 5;
67//! let my_span = span!(Level::TRACE, "my_span", my_var);
68//!
69//! // `my_span` exists but has not been entered.
70//!
71//! // Enter `my_span`...
72//! let _enter = my_span.enter();
73//!
74//! // Perform some work inside of the context of `my_span`...
75//! // Dropping the `_enter` guard will exit the span.
76//!```
77//!
78//! <div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;">
79//!
80//!  **Warning**: In asynchronous code that uses async/await syntax,
81//!  [`Span::enter`] may produce incorrect traces if the returned drop
82//!  guard is held across an await point. See
83//!  [the method documentation][Span#in-asynchronous-code] for details.
84//!
85//! </pre></div>
86//!
87//! `in_scope` takes a closure or function pointer and executes it inside the
88//! span.
89//! ```
90//! # use tracing::{Level, span};
91//! let my_var: u64 = 5;
92//! let my_span = span!(Level::TRACE, "my_span", my_var = &my_var);
93//!
94//! my_span.in_scope(|| {
95//!     // perform some work in the context of `my_span`...
96//! });
97//!
98//! // Perform some work outside of the context of `my_span`...
99//!
100//! my_span.in_scope(|| {
101//!     // Perform some more work in the context of `my_span`.
102//! });
103//! ```
104//!
105//! <div class="example-wrap" style="display:inline-block">
106//! <pre class="ignore" style="white-space:normal;font:inherit;">
107//! <strong>Note</strong>: Since entering a span takes <code>&self</code>, and
108//! <code>Span</code>s are <code>Clone</code>, <code>Send</code>, and
109//! <code>Sync</code>, it is entirely valid for multiple threads to enter the
110//! same span concurrently.
111//! </pre></div>
112//!
113//! ## Span Relationships
114//!
115//! Spans form a tree structure β€” unless it is a root span, all spans have a
116//! _parent_, and may have one or more _children_. When a new span is created,
117//! the current span becomes the new span's parent. The total execution time of
118//! a span consists of the time spent in that span and in the entire subtree
119//! represented by its children. Thus, a parent span always lasts for at least
120//! as long as the longest-executing span in its subtree.
121//!
122//! ```
123//! # use tracing::{Level, span};
124//! // this span is considered the "root" of a new trace tree:
125//! span!(Level::INFO, "root").in_scope(|| {
126//!     // since we are now inside "root", this span is considered a child
127//!     // of "root":
128//!     span!(Level::DEBUG, "outer_child").in_scope(|| {
129//!         // this span is a child of "outer_child", which is in turn a
130//!         // child of "root":
131//!         span!(Level::TRACE, "inner_child").in_scope(|| {
132//!             // and so on...
133//!         });
134//!     });
135//!     // another span created here would also be a child of "root".
136//! });
137//!```
138//!
139//! In addition, the parent of a span may be explicitly specified in
140//! the `span!` macro. For example:
141//!
142//! ```rust
143//! # use tracing::{Level, span};
144//! // Create, but do not enter, a span called "foo".
145//! let foo = span!(Level::INFO, "foo");
146//!
147//! // Create and enter a span called "bar".
148//! let bar = span!(Level::INFO, "bar");
149//! let _enter = bar.enter();
150//!
151//! // Although we have currently entered "bar", "baz"'s parent span
152//! // will be "foo".
153//! let baz = span!(parent: &foo, Level::INFO, "baz");
154//! ```
155//!
156//! A child span should typically be considered _part_ of its parent. For
157//! example, if a collector is recording the length of time spent in various
158//! spans, it should generally include the time spent in a span's children as
159//! part of that span's duration.
160//!
161//! In addition to having zero or one parent, a span may also _follow from_ any
162//! number of other spans. This indicates a causal relationship between the span
163//! and the spans that it follows from, but a follower is *not* typically
164//! considered part of the duration of the span it follows. Unlike the parent, a
165//! span may record that it follows from another span after it is created, using
166//! the [`follows_from`] method.
167//!
168//! As an example, consider a listener task in a server. As the listener accepts
169//! incoming connections, it spawns new tasks that handle those connections. We
170//! might want to have a span representing the listener, and instrument each
171//! spawned handler task with its own span. We would want our instrumentation to
172//! record that the handler tasks were spawned as a result of the listener task.
173//! However, we might not consider the handler tasks to be _part_ of the time
174//! spent in the listener task, so we would not consider those spans children of
175//! the listener span. Instead, we would record that the handler tasks follow
176//! from the listener, recording the causal relationship but treating the spans
177//! as separate durations.
178//!
179//! ## Closing Spans
180//!
181//! Execution may enter and exit a span multiple times before that span is
182//! _closed_. Consider, for example, a future which has an associated
183//! span and enters that span every time it is polled:
184//! ```rust
185//! # use std::future::Future;
186//! # use std::task::{Context, Poll};
187//! # use std::pin::Pin;
188//! struct MyFuture {
189//!    // data
190//!    span: tracing::Span,
191//! }
192//!
193//! impl Future for MyFuture {
194//!     type Output = ();
195//!
196//!     fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
197//!         let _enter = self.span.enter();
198//!         // Do actual future work...
199//! # Poll::Ready(())
200//!     }
201//! }
202//! ```
203//!
204//! If this future was spawned on an executor, it might yield one or more times
205//! before `poll` returns [`Poll::Ready`]. If the future were to yield, then
206//! the executor would move on to poll the next future, which may _also_ enter
207//! an associated span or series of spans. Therefore, it is valid for a span to
208//! be entered repeatedly before it completes. Only the time when that span or
209//! one of its children was the current span is considered to be time spent in
210//! that span. A span which is not executing and has not yet been closed is said
211//! to be _idle_.
212//!
213//! Because spans may be entered and exited multiple times before they close,
214//! [collector]s have separate trait methods which are called to notify them
215//! of span exits and when span handles are dropped. When execution exits a
216//! span, [`exit`] will always be called with that span's ID to notify the
217//! collector that the span has been exited. When span handles are dropped, the
218//! [`drop_span`] method is called with that span's ID. The collector may use
219//! this to determine whether or not the span will be entered again.
220//!
221//! If there is only a single handle with the capacity to exit a span, dropping
222//! that handle "closes" the span, since the capacity to enter it no longer
223//! exists. For example:
224//! ```
225//! # use tracing::{Level, span};
226//! {
227//!     span!(Level::TRACE, "my_span").in_scope(|| {
228//!         // perform some work in the context of `my_span`...
229//!     }); // --> Collect::exit(my_span)
230//!
231//!     // The handle to `my_span` only lives inside of this block; when it is
232//!     // dropped, the collector will be informed via `drop_span`.
233//!
234//! } // --> Collect::drop_span(my_span)
235//! ```
236//!
237//! However, if multiple handles exist, the span can still be re-entered even if
238//! one or more is dropped. For determining when _all_ handles to a span have
239//! been dropped, collectors have a [`clone_span`] method, which is called
240//! every time a span handle is cloned. Combined with `drop_span`, this may be
241//! used to track the number of handles to a given span β€” if `drop_span` has
242//! been called one more time than the number of calls to `clone_span` for a
243//! given ID, then no more handles to the span with that ID exist. The
244//! collector may then treat it as closed.
245//!
246//! # When to use spans
247//!
248//! As a rule of thumb, spans should be used to represent discrete units of work
249//! (e.g., a given request's lifetime in a server) or periods of time spent in a
250//! given context (e.g., time spent interacting with an instance of an external
251//! system, such as a database).
252//!
253//! Which scopes in a program correspond to new spans depend somewhat on user
254//! intent. For example, consider the case of a loop in a program. Should we
255//! construct one span and perform the entire loop inside of that span, like:
256//!
257//! ```rust
258//! # use tracing::{Level, span};
259//! # let n = 1;
260//! let span = span!(Level::TRACE, "my_loop");
261//! let _enter = span.enter();
262//! for i in 0..n {
263//!     # let _ = i;
264//!     // ...
265//! }
266//! ```
267//! Or, should we create a new span for each iteration of the loop, as in:
268//! ```rust
269//! # use tracing::{Level, span};
270//! # let n = 1u64;
271//! for i in 0..n {
272//!     let span = span!(Level::TRACE, "my_loop", iteration = i);
273//!     let _enter = span.enter();
274//!     // ...
275//! }
276//! ```
277//!
278//! Depending on the circumstances, we might want to do either, or both. For
279//! example, if we want to know how long was spent in the loop overall, we would
280//! create a single span around the entire loop; whereas if we wanted to know how
281//! much time was spent in each individual iteration, we would enter a new span
282//! on every iteration.
283//!
284//! [fields]: super::field
285//! [Metadata]: super::Metadata
286//! [verbosity level]: super::Level
287//! [`Poll::Ready`]: std::task::Poll::Ready
288//! [`span!`]: super::span!
289//! [`trace_span!`]: super::trace_span!
290//! [`debug_span!`]: super::debug_span!
291//! [`info_span!`]: super::info_span!
292//! [`warn_span!`]: super::warn_span!
293//! [`error_span!`]: super::error_span!
294//! [`clone_span`]: super::collect::Collect::clone_span()
295//! [`drop_span`]: super::collect::Collect::drop_span()
296//! [`exit`]: super::collect::Collect::exit
297//! [collector]: super::collect::Collect
298//! [`enter`]: Span::enter()
299//! [`in_scope`]: Span::in_scope()
300//! [`follows_from`]: Span::follows_from()
301//! [guard]: Entered
302//! [parent]: #span-relationships
303pub use tracing_core::span::{Attributes, Id, Record};
304
305use crate::{
306    dispatch::{self, Dispatch},
307    field, Metadata,
308};
309use core::{
310    cmp, fmt,
311    hash::{Hash, Hasher},
312    marker::PhantomData,
313    mem,
314    ops::Deref,
315};
316
317/// Trait implemented by types which have a span `Id`.
318pub trait AsId: crate::sealed::Sealed {
319    /// Returns the `Id` of the span that `self` corresponds to, or `None` if
320    /// this corresponds to a disabled span.
321    fn as_id(&self) -> Option<&Id>;
322}
323
324/// A handle representing a span, with the capability to enter the span if it
325/// exists.
326///
327/// If the span was rejected by the current `Collector`'s filter, entering the
328/// span will silently do nothing. Thus, the handle can be used in the same
329/// manner regardless of whether or not the trace is currently being collected.
330#[derive(Clone)]
331pub struct Span {
332    /// A handle used to enter the span when it is not executing.
333    ///
334    /// If this is `None`, then the span has either closed or was never enabled.
335    inner: Option<Inner>,
336    /// Metadata describing the span.
337    ///
338    /// This might be `Some` even if `inner` is `None`, in the case that the
339    /// span is disabled but the metadata is needed for `log` support.
340    meta: Option<&'static Metadata<'static>>,
341}
342
343/// A handle representing the capacity to enter a span which is known to exist.
344///
345/// Unlike `Span`, this type is only constructed for spans which _have_ been
346/// enabled by the current filter. This type is primarily used for implementing
347/// span handles; users should typically not need to interact with it directly.
348#[derive(Debug)]
349pub(crate) struct Inner {
350    /// The span's ID, as provided by `collector`.
351    id: Id,
352
353    /// The collector that will receive events relating to this span.
354    ///
355    /// This should be the same collector that provided this span with its
356    /// `id`.
357    collector: Dispatch,
358}
359
360/// A guard representing a span which has been entered and is currently
361/// executing.
362///
363/// When the guard is dropped, the span will be exited.
364///
365/// This is returned by the [`Span::enter`] function.
366///
367/// [`Span::enter`]: super::Span::enter()
368#[derive(Debug)]
369#[must_use = "once a span has been entered, it should be exited"]
370pub struct Entered<'a> {
371    span: &'a Span,
372
373    /// ```compile_fail
374    /// use tracing::span::*;
375    /// trait AssertSend: Send {}
376    ///
377    /// impl AssertSend for Entered<'_> {}
378    /// ```
379    _not_send: PhantomNotSend,
380}
381
382/// An owned version of [`Entered`], a guard representing a span which has been
383/// entered and is currently executing.
384///
385/// When the guard is dropped, the span will be exited.
386///
387/// This is returned by the [`Span::entered`] function.
388///
389/// [`Span::entered`]: super::Span::entered()
390#[derive(Debug)]
391#[must_use = "once a span has been entered, it should be exited"]
392pub struct EnteredSpan {
393    span: Span,
394
395    /// ```compile_fail
396    /// use tracing::span::*;
397    /// trait AssertSend: Send {}
398    ///
399    /// impl AssertSend for EnteredSpan {}
400    /// ```
401    _not_send: PhantomNotSend,
402}
403
404/// `log` target for all span lifecycle (creation/enter/exit/close) records.
405#[cfg(feature = "log")]
406const LIFECYCLE_LOG_TARGET: &str = "tracing::span";
407/// `log` target for span activity (enter/exit) records.
408#[cfg(feature = "log")]
409const ACTIVITY_LOG_TARGET: &str = "tracing::span::active";
410
411// ===== impl Span =====
412
413impl Span {
414    /// Constructs a new `Span` with the given [metadata] and set of
415    /// [field values].
416    ///
417    /// The new span will be constructed by the currently-active [collector],
418    /// with the current span as its parent (if one exists).
419    ///
420    /// After the span is constructed, [field values] and/or [`follows_from`]
421    /// annotations may be added to it.
422    ///
423    /// [metadata]: mod@super::metadata
424    /// [collector]: super::collect::Collect
425    /// [field values]: super::field::ValueSet
426    /// [`follows_from`]: super::Span::follows_from()
427    pub fn new(meta: &'static Metadata<'static>, values: &field::ValueSet<'_>) -> Span {
428        dispatch::get_default(|dispatch| Self::new_with(meta, values, dispatch))
429    }
430
431    #[inline]
432    #[doc(hidden)]
433    pub fn new_with(
434        meta: &'static Metadata<'static>,
435        values: &field::ValueSet<'_>,
436        dispatch: &Dispatch,
437    ) -> Span {
438        let new_span = Attributes::new(meta, values);
439        Self::make_with(meta, new_span, dispatch)
440    }
441
442    /// Constructs a new `Span` as the root of its own trace tree, with the
443    /// given [metadata] and set of [field values].
444    ///
445    /// After the span is constructed, [field values] and/or [`follows_from`]
446    /// annotations may be added to it.
447    ///
448    /// [metadata]: mod@super::metadata
449    /// [field values]: super::field::ValueSet
450    /// [`follows_from`]: super::Span::follows_from()
451    pub fn new_root(meta: &'static Metadata<'static>, values: &field::ValueSet<'_>) -> Span {
452        dispatch::get_default(|dispatch| Self::new_root_with(meta, values, dispatch))
453    }
454
455    #[inline]
456    #[doc(hidden)]
457    pub fn new_root_with(
458        meta: &'static Metadata<'static>,
459        values: &field::ValueSet<'_>,
460        dispatch: &Dispatch,
461    ) -> Span {
462        let new_span = Attributes::new_root(meta, values);
463        Self::make_with(meta, new_span, dispatch)
464    }
465
466    /// Constructs a new `Span` as child of the given parent span, with the
467    /// given [metadata] and set of [field values].
468    ///
469    /// After the span is constructed, [field values] and/or [`follows_from`]
470    /// annotations may be added to it.
471    ///
472    /// [metadata]: mod@super::metadata
473    /// [field values]: super::field::ValueSet
474    /// [`follows_from`]: super::Span::follows_from()
475    pub fn child_of(
476        parent: impl Into<Option<Id>>,
477        meta: &'static Metadata<'static>,
478        values: &field::ValueSet<'_>,
479    ) -> Span {
480        let mut parent = parent.into();
481        dispatch::get_default(move |dispatch| {
482            Self::child_of_with(Option::take(&mut parent), meta, values, dispatch)
483        })
484    }
485
486    #[inline]
487    #[doc(hidden)]
488    pub fn child_of_with(
489        parent: impl Into<Option<Id>>,
490        meta: &'static Metadata<'static>,
491        values: &field::ValueSet<'_>,
492        dispatch: &Dispatch,
493    ) -> Span {
494        let new_span = match parent.into() {
495            Some(parent) => Attributes::child_of(parent, meta, values),
496            None => Attributes::new_root(meta, values),
497        };
498        Self::make_with(meta, new_span, dispatch)
499    }
500
501    /// Constructs a new disabled span with the given `Metadata`.
502    ///
503    /// This should be used when a span is constructed from a known callsite,
504    /// but the collector indicates that it is disabled.
505    ///
506    /// Entering, exiting, and recording values on this span will not notify the
507    /// `Collector` but _may_ record log messages if the `log` feature flag is
508    /// enabled.
509    #[inline(always)]
510    pub fn new_disabled(meta: &'static Metadata<'static>) -> Span {
511        Self {
512            inner: None,
513            meta: Some(meta),
514        }
515    }
516
517    /// Constructs a new span that is *completely disabled*.
518    ///
519    /// This can be used rather than `Option<Span>` to represent cases where a
520    /// span is not present.
521    ///
522    /// Entering, exiting, and recording values on this span will do nothing.
523    #[inline(always)]
524    pub const fn none() -> Span {
525        Self {
526            inner: None,
527            meta: None,
528        }
529    }
530
531    /// Returns a handle to the span [considered by the `Collector`] to be the
532    /// current span.
533    ///
534    /// If the collector indicates that it does not track the current span, or
535    /// that the thread from which this function is called is not currently
536    /// inside a span, the returned span will be disabled.
537    ///
538    /// [considered by the `Collector`]: super::collect::Collect::current_span()
539    pub fn current() -> Span {
540        dispatch::get_default(|dispatch| {
541            if let Some((id, meta)) = dispatch.current_span().into_inner() {
542                let id = dispatch.clone_span(&id);
543                Self {
544                    inner: Some(Inner::new(id, dispatch)),
545                    meta: Some(meta),
546                }
547            } else {
548                Self::none()
549            }
550        })
551    }
552
553    fn make_with(
554        meta: &'static Metadata<'static>,
555        new_span: Attributes<'_>,
556        dispatch: &Dispatch,
557    ) -> Span {
558        let attrs = &new_span;
559        let id = dispatch.new_span(attrs);
560        let inner = Some(Inner::new(id, dispatch));
561
562        let span = Self {
563            inner,
564            meta: Some(meta),
565        };
566
567        if_log_enabled! { *meta.level(), {
568            let target = if attrs.is_empty() {
569                LIFECYCLE_LOG_TARGET
570            } else {
571                meta.target()
572            };
573            let values = attrs.values();
574            span.log(
575                target,
576                level_to_log!(*meta.level()),
577                format_args!("++ {};{}", meta.name(), crate::log::LogValueSet { values, is_first: false }),
578            );
579        }}
580
581        span
582    }
583
584    /// Enters this span, returning a guard that will exit the span when dropped.
585    ///
586    /// If this span is enabled by the current collector, then this function will
587    /// call [`Collect::enter`] with the span's [`Id`], and dropping the guard
588    /// will call [`Collect::exit`]. If the span is disabled, this does
589    /// nothing.
590    ///
591    /// <div class="example-wrap" style="display:inline-block">
592    /// <pre class="ignore" style="white-space:normal;font:inherit;">
593    ///
594    /// **Note**: The returned [`Entered`] guard does not
595    /// implement `Send`. Dropping the guard will exit *this* span,
596    /// and if the guard is sent to another thread and dropped there, that thread may
597    /// never have entered this span. Thus, `Entered` should not be sent
598    /// between threads.
599    ///
600    /// </pre></div>
601    ///
602    /// **Warning**: in asynchronous code that uses [async/await syntax][syntax],
603    /// [`Span::enter`] should be used very carefully or avoided entirely. Holding
604    /// the drop guard returned by `Span::enter` across `.await` points will
605    /// result in incorrect traces. For example,
606    ///
607    /// ```
608    /// # use tracing::info_span;
609    /// # async fn some_other_async_function() {}
610    /// async fn my_async_function() {
611    ///     let span = info_span!("my_async_function");
612    ///
613    ///     // WARNING: This span will remain entered until this
614    ///     // guard is dropped...
615    ///     let _enter = span.enter();
616    ///     // ...but the `await` keyword may yield, causing the
617    ///     // runtime to switch to another task, while remaining in
618    ///     // this span!
619    ///     some_other_async_function().await
620    ///
621    ///     // ...
622    /// }
623    /// ```
624    ///
625    /// The drop guard returned by `Span::enter` exits the span when it is
626    /// dropped. When an async function or async block yields at an `.await`
627    /// point, the current scope is _exited_, but values in that scope are
628    /// **not** dropped (because the async block will eventually resume
629    /// execution from that await point). This means that _another_ task will
630    /// begin executing while _remaining_ in the entered span. This results in
631    /// an incorrect trace.
632    ///
633    /// Instead of using `Span::enter` in asynchronous code, prefer the
634    /// following:
635    ///
636    /// * To enter a span for a synchronous section of code within an async
637    ///   block or function, prefer [`Span::in_scope`]. Since `in_scope` takes a
638    ///   synchronous closure and exits the span when the closure returns, the
639    ///   span will always be exited before the next await point. For example:
640    ///   ```
641    ///   # use tracing::info_span;
642    ///   # async fn some_other_async_function(_: ()) {}
643    ///   async fn my_async_function() {
644    ///       let span = info_span!("my_async_function");
645    ///
646    ///       let some_value = span.in_scope(|| {
647    ///           // run some synchronous code inside the span...
648    ///       });
649    ///
650    ///       // This is okay! The span has already been exited before we reach
651    ///       // the await point.
652    ///       some_other_async_function(some_value).await;
653    ///
654    ///       // ...
655    ///   }
656    ///   ```
657    /// * For instrumenting asynchronous code, `tracing` provides the
658    ///   [`Future::instrument` combinator][instrument] for
659    ///   attaching a span to a future (async function or block). This will
660    ///   enter the span _every_ time the future is polled, and exit it whenever
661    ///   the future yields.
662    ///
663    ///   `Instrument` can be used with an async block inside an async function:
664    ///   ```ignore
665    ///   # use tracing::info_span;
666    ///   use tracing::Instrument;
667    ///
668    ///   # async fn some_other_async_function() {}
669    ///   async fn my_async_function() {
670    ///       let span = info_span!("my_async_function");
671    ///       async move {
672    ///          // This is correct! If we yield here, the span will be exited,
673    ///          // and re-entered when we resume.
674    ///          some_other_async_function().await;
675    ///
676    ///          //more asynchronous code inside the span...
677    ///
678    ///       }
679    ///         // instrument the async block with the span...
680    ///         .instrument(span)
681    ///         // ...and await it.
682    ///         .await
683    ///   }
684    ///   ```
685    ///
686    ///   It can also be used to instrument calls to async functions at the
687    ///   callsite:
688    ///   ```ignore
689    ///   # use tracing::debug_span;
690    ///   use tracing::Instrument;
691    ///
692    ///   # async fn some_other_async_function() {}
693    ///   async fn my_async_function() {
694    ///       let some_value = some_other_async_function()
695    ///          .instrument(debug_span!("some_other_async_function"))
696    ///          .await;
697    ///
698    ///       // ...
699    ///   }
700    ///   ```
701    ///
702    /// * The [`#[instrument]` attribute macro][attr] can automatically generate
703    ///   correct code when used on an async function:
704    ///
705    ///   ```ignore
706    ///   # async fn some_other_async_function() {}
707    ///   #[tracing::instrument(level = "info")]
708    ///   async fn my_async_function() {
709    ///
710    ///       // This is correct! If we yield here, the span will be exited,
711    ///       // and re-entered when we resume.
712    ///       some_other_async_function().await;
713    ///
714    ///       // ...
715    ///
716    ///   }
717    ///   ```
718    ///
719    /// [syntax]: https://rust-lang.github.io/async-book/01_getting_started/04_async_await_primer.html
720    /// [instrument]: crate::Instrument
721    /// [attr]: macro@crate::instrument
722    ///
723    /// # Examples
724    ///
725    /// ```
726    /// # use tracing::{span, Level};
727    /// let span = span!(Level::INFO, "my_span");
728    /// let guard = span.enter();
729    ///
730    /// // code here is within the span
731    ///
732    /// drop(guard);
733    ///
734    /// // code here is no longer within the span
735    ///
736    /// ```
737    ///
738    /// Guards need not be explicitly dropped:
739    ///
740    /// ```
741    /// # use tracing::trace_span;
742    /// fn my_function() -> String {
743    ///     // enter a span for the duration of this function.
744    ///     let span = trace_span!("my_function");
745    ///     let _enter = span.enter();
746    ///
747    ///     // anything happening in functions we call is still inside the span...
748    ///     my_other_function();
749    ///
750    ///     // returning from the function drops the guard, exiting the span.
751    ///     return "Hello world".to_owned();
752    /// }
753    ///
754    /// fn my_other_function() {
755    ///     // ...
756    /// }
757    /// ```
758    ///
759    /// Sub-scopes may be created to limit the duration for which the span is
760    /// entered:
761    ///
762    /// ```
763    /// # use tracing::{info, info_span};
764    /// let span = info_span!("my_great_span");
765    ///
766    /// {
767    ///     let _enter = span.enter();
768    ///
769    ///     // this event occurs inside the span.
770    ///     info!("i'm in the span!");
771    ///
772    ///     // exiting the scope drops the guard, exiting the span.
773    /// }
774    ///
775    /// // this event is not inside the span.
776    /// info!("i'm outside the span!")
777    /// ```
778    ///
779    /// [`Collect::enter`]: super::collect::Collect::enter()
780    /// [`Collect::exit`]: super::collect::Collect::exit()
781    /// [`Id`]: super::Id
782    #[inline(always)]
783    pub fn enter(&self) -> Entered<'_> {
784        self.do_enter();
785        Entered {
786            span: self,
787            _not_send: PhantomNotSend,
788        }
789    }
790
791    /// Enters this span, consuming it and returning a [guard][`EnteredSpan`]
792    /// that will exit the span when dropped.
793    ///
794    /// If this span is enabled by the current collector, then this function will
795    /// call [`Collect::enter`] with the span's [`Id`], and dropping the guard
796    /// will call [`Collect::exit`]. If the span is disabled, this does
797    /// nothing.
798    ///
799    /// This is similar to the [`Span::enter`] method, except that it moves the
800    /// span by value into the returned guard, rather than borrowing it.
801    /// Therefore, this method can be used to create and enter a span in a
802    /// single expression, without requiring a `let`-binding. For example:
803    ///
804    /// ```
805    /// # use tracing::info_span;
806    /// let _span = info_span!("something_interesting").entered();
807    /// ```
808    /// rather than:
809    /// ```
810    /// # use tracing::info_span;
811    /// let span = info_span!("something_interesting");
812    /// let _e = span.enter();
813    /// ```
814    ///
815    /// Furthermore, `entered` may be used when the span must be stored in some
816    /// other struct or be passed to a function while remaining entered.
817    ///
818    /// <div class="example-wrap" style="display:inline-block">
819    /// <pre class="ignore" style="white-space:normal;font:inherit;">
820    ///
821    /// **Note**: The returned [`EnteredSpan`] guard does not
822    /// implement `Send`. Dropping the guard will exit *this* span,
823    /// and if the guard is sent to another thread and dropped there, that thread may
824    /// never have entered this span. Thus, `EnteredSpan`s should not be sent
825    /// between threads.
826    ///
827    /// </pre></div>
828    ///
829    /// **Warning**: in asynchronous code that uses [async/await syntax][syntax],
830    /// [`Span::entered`] should be used very carefully or avoided entirely. Holding
831    /// the drop guard returned by `Span::entered` across `.await` points will
832    /// result in incorrect traces. See the documentation for the
833    /// [`Span::enter`] method for details.
834    ///
835    /// [syntax]: https://rust-lang.github.io/async-book/01_getting_started/04_async_await_primer.html
836    ///
837    /// # Examples
838    ///
839    /// The returned guard can be [explicitly exited][EnteredSpan::exit],
840    /// returning the un-entered span:
841    ///
842    /// ```
843    /// # use tracing::{Level, span};
844    /// let span = span!(Level::INFO, "doing_something").entered();
845    ///
846    /// // code here is within the span
847    ///
848    /// // explicitly exit the span, returning it
849    /// let span = span.exit();
850    ///
851    /// // code here is no longer within the span
852    ///
853    /// // enter the span again
854    /// let span = span.entered();
855    ///
856    /// // now we are inside the span once again
857    /// ```
858    ///
859    /// Guards need not be explicitly dropped:
860    ///
861    /// ```
862    /// # use tracing::trace_span;
863    /// fn my_function() -> String {
864    ///     // enter a span for the duration of this function.
865    ///     let span = trace_span!("my_function").entered();
866    ///
867    ///     // anything happening in functions we call is still inside the span...
868    ///     my_other_function();
869    ///
870    ///     // returning from the function drops the guard, exiting the span.
871    ///     return "Hello world".to_owned();
872    /// }
873    ///
874    /// fn my_other_function() {
875    ///     // ...
876    /// }
877    /// ```
878    ///
879    /// Since the [`EnteredSpan`] guard can dereference to the [`Span`] itself,
880    /// the span may still be accessed while entered. For example:
881    ///
882    /// ```rust
883    /// # use tracing::info_span;
884    /// use tracing::field;
885    ///
886    /// // create the span with an empty field, and enter it.
887    /// let span = info_span!("my_span", some_field = field::Empty).entered();
888    ///
889    /// // we can still record a value for the field while the span is entered.
890    /// span.record("some_field", &"hello world!");
891    /// ```
892    ///
893    /// [`Collect::enter`]: super::collect::Collect::enter()
894    /// [`Collect::exit`]: super::collect::Collect::exit()
895    /// [`Id`]: super::Id
896    #[inline(always)]
897    pub fn entered(self) -> EnteredSpan {
898        self.do_enter();
899        EnteredSpan {
900            span: self,
901            _not_send: PhantomNotSend,
902        }
903    }
904
905    /// Returns this span, if it was [enabled] by the current [collector], or
906    /// the [current span] (whose lexical distance may be further than expected),
907    ///  if this span [is disabled].
908    ///
909    /// This method can be useful when propagating spans to spawned threads or
910    /// [async tasks]. Consider the following:
911    ///
912    /// ```
913    /// let _parent_span = tracing::info_span!("parent").entered();
914    ///
915    /// // ...
916    ///
917    /// let child_span = tracing::debug_span!("child");
918    ///
919    /// std::thread::spawn(move || {
920    ///     let _entered = child_span.entered();
921    ///
922    ///     tracing::info!("spawned a thread!");
923    ///
924    ///     // ...
925    /// });
926    /// ```
927    ///
928    /// If the current [collector] enables the [`DEBUG`] level, then both
929    /// the "parent" and "child" spans will be enabled. Thus, when the "spawned
930    /// a thread!" event occurs, it will be inside of the "child" span. Because
931    /// "parent" is the parent of "child", the event will _also_ be inside of
932    /// "parent".
933    ///
934    /// However, if the collector only enables the [`INFO`] level, the "child"
935    /// span will be disabled. When the thread is spawned, the
936    /// `child_span.entered()` call will do nothing, since "child" is not
937    /// enabled. In this case, the "spawned a thread!" event occurs outside of
938    /// *any* span, since the "child" span was responsible for propagating its
939    /// parent to the spawned thread.
940    ///
941    /// If this is not the desired behavior, `Span::or_current` can be used to
942    /// ensure that the "parent" span is propagated in both cases, either as a
943    /// parent of "child" _or_ directly. For example:
944    ///
945    /// ```
946    /// let _parent_span = tracing::info_span!("parent").entered();
947    ///
948    /// // ...
949    ///
950    /// // If DEBUG is enabled, then "child" will be enabled, and `or_current`
951    /// // returns "child". Otherwise, if DEBUG is not enabled, "child" will be
952    /// // disabled, and `or_current` returns "parent".
953    /// let child_span = tracing::debug_span!("child").or_current();
954    ///
955    /// std::thread::spawn(move || {
956    ///     let _entered = child_span.entered();
957    ///
958    ///     tracing::info!("spawned a thread!");
959    ///
960    ///     // ...
961    /// });
962    /// ```
963    ///
964    /// When spawning [asynchronous tasks][async tasks], `Span::or_current` can
965    /// be used similarly, in combination with [`instrument`]:
966    ///
967    /// ```
968    /// use tracing::Instrument;
969    /// # // lol
970    /// # mod tokio {
971    /// #     pub(super) fn spawn(_: impl std::future::Future) {}
972    /// # }
973    ///
974    /// let _parent_span = tracing::info_span!("parent").entered();
975    ///
976    /// // ...
977    ///
978    /// let child_span = tracing::debug_span!("child");
979    ///
980    /// tokio::spawn(
981    ///     async {
982    ///         tracing::info!("spawned a task!");
983    ///
984    ///         // ...
985    ///
986    ///     }.instrument(child_span.or_current())
987    /// );
988    /// ```
989    ///
990    /// In general, `or_current` should be preferred over nesting an
991    /// [`instrument`]  call inside of an [`in_current_span`] call, as using
992    /// `or_current` will be more efficient.
993    ///
994    /// ```
995    /// use tracing::Instrument;
996    /// # // lol
997    /// # mod tokio {
998    /// #     pub(super) fn spawn(_: impl std::future::Future) {}
999    /// # }
1000    /// async fn my_async_fn() {
1001    ///     // ...
1002    /// }
1003    ///
1004    /// let _parent_span = tracing::info_span!("parent").entered();
1005    ///
1006    /// // Do this:
1007    /// tokio::spawn(
1008    ///     my_async_fn().instrument(tracing::debug_span!("child").or_current())
1009    /// );
1010    ///
1011    /// // ...rather than this:
1012    /// tokio::spawn(
1013    ///     my_async_fn()
1014    ///         .instrument(tracing::debug_span!("child"))
1015    ///         .in_current_span()
1016    /// );
1017    /// ```
1018    ///
1019    /// [enabled]: crate::collect::Collect::enabled
1020    /// [collector]: crate::collect::Collect
1021    /// [current span]: Span::current
1022    /// [is disabled]: Span::is_disabled
1023    /// [`INFO`]: crate::Level::INFO
1024    /// [`DEBUG`]: crate::Level::DEBUG
1025    /// [async tasks]: std::task
1026    /// [`instrument`]: crate::instrument::Instrument::instrument
1027    /// [`in_current_span`]: crate::instrument::Instrument::in_current_span
1028    pub fn or_current(self) -> Self {
1029        if self.is_disabled() {
1030            return Self::current();
1031        }
1032        self
1033    }
1034
1035    #[inline(always)]
1036    fn do_enter(&self) {
1037        if let Some(inner) = self.inner.as_ref() {
1038            inner.collector.enter(&inner.id);
1039        }
1040
1041        if_log_enabled! { crate::Level::TRACE, {
1042            if let Some(_meta) = self.meta {
1043                self.log(ACTIVITY_LOG_TARGET, log::Level::Trace, format_args!("-> {};", _meta.name()));
1044            }
1045        }}
1046    }
1047
1048    // Called from [`Entered`] and [`EnteredSpan`] drops.
1049    //
1050    // Running this behaviour on drop rather than with an explicit function
1051    // call means that spans may still be exited when unwinding.
1052    #[inline(always)]
1053    fn do_exit(&self) {
1054        if let Some(inner) = self.inner.as_ref() {
1055            inner.collector.exit(&inner.id);
1056        }
1057
1058        if_log_enabled! { crate::Level::TRACE, {
1059            if let Some(_meta) = self.meta {
1060                self.log(ACTIVITY_LOG_TARGET, log::Level::Trace, format_args!("<- {};", _meta.name()));
1061            }
1062        }}
1063    }
1064
1065    /// Executes the given function in the context of this span.
1066    ///
1067    /// If this span is enabled, then this function enters the span, invokes `f`
1068    /// and then exits the span. If the span is disabled, `f` will still be
1069    /// invoked, but in the context of the currently-executing span (if there is
1070    /// one).
1071    ///
1072    /// Returns the result of evaluating `f`.
1073    ///
1074    /// # Examples
1075    ///
1076    /// ```
1077    /// # use tracing::{trace, span, Level};
1078    /// let my_span = span!(Level::TRACE, "my_span");
1079    ///
1080    /// my_span.in_scope(|| {
1081    ///     // this event occurs within the span.
1082    ///     trace!("i'm in the span!");
1083    /// });
1084    ///
1085    /// // this event occurs outside the span.
1086    /// trace!("i'm not in the span!");
1087    /// ```
1088    ///
1089    /// Calling a function and returning the result:
1090    /// ```
1091    /// # use tracing::{info_span, Level};
1092    /// fn hello_world() -> String {
1093    ///     "Hello world!".to_owned()
1094    /// }
1095    ///
1096    /// let span = info_span!("hello_world");
1097    /// // the span will be entered for the duration of the call to
1098    /// // `hello_world`.
1099    /// let a_string = span.in_scope(hello_world);
1100    ///
1101    pub fn in_scope<F: FnOnce() -> T, T>(&self, f: F) -> T {
1102        let _enter = self.enter();
1103        f()
1104    }
1105
1106    /// Returns a [`Field`](super::field::Field) for the field with the
1107    /// given `name`, if one exists,
1108    pub fn field<Q>(&self, field: &Q) -> Option<field::Field>
1109    where
1110        Q: field::AsField + ?Sized,
1111    {
1112        self.metadata().and_then(|meta| field.as_field(meta))
1113    }
1114
1115    /// Returns true if this `Span` has a field for the given
1116    /// [`Field`](super::field::Field) or field name.
1117    #[inline]
1118    pub fn has_field<Q>(&self, field: &Q) -> bool
1119    where
1120        Q: field::AsField + ?Sized,
1121    {
1122        self.field(field).is_some()
1123    }
1124
1125    /// Records that the field described by `field` has the value `value`.
1126    ///
1127    /// This may be used with [`field::Empty`] to declare fields whose values
1128    /// are not known when the span is created, and record them later:
1129    /// ```
1130    /// use tracing::{trace_span, field};
1131    ///
1132    /// // Create a span with two fields: `greeting`, with the value "hello world", and
1133    /// // `parting`, without a value.
1134    /// let span = trace_span!("my_span", greeting = "hello world", parting = field::Empty);
1135    ///
1136    /// // ...
1137    ///
1138    /// // Now, record a value for parting as well.
1139    /// // (note that the field name is passed as a string slice)
1140    /// span.record("parting", "goodbye world!");
1141    /// ```
1142    /// However, it may also be used to record a _new_ value for a field whose
1143    /// value was already recorded:
1144    /// ```
1145    /// use tracing::info_span;
1146    /// # fn do_something() -> Result<(), ()> { Err(()) }
1147    ///
1148    /// // Initially, let's assume that our attempt to do something is going okay...
1149    /// let span = info_span!("doing_something", is_okay = true);
1150    /// let _e = span.enter();
1151    ///
1152    /// match do_something() {
1153    ///     Ok(something) => {
1154    ///         // ...
1155    ///     }
1156    ///     Err(_) => {
1157    ///         // Things are no longer okay!
1158    ///         span.record("is_okay", false);
1159    ///     }
1160    /// }
1161    /// ```
1162    ///
1163    /// <div class="example-wrap" style="display:inline-block">
1164    /// <pre class="ignore" style="white-space:normal;font:inherit;">
1165    ///
1166    /// **Note**: The fields associated with a span are part of its [`Metadata`].
1167    /// The [`Metadata`] describing a particular
1168    /// span is constructed statically when the span is created and cannot be extended later to
1169    /// add new fields. Therefore, you cannot record a value for a field that was not specified
1170    /// when the span was created:
1171    ///
1172    /// </pre></div>
1173    ///
1174    /// ```
1175    /// use tracing::{trace_span, field};
1176    ///
1177    /// // Create a span with two fields: `greeting`, with the value "hello world", and
1178    /// // `parting`, without a value.
1179    /// let span = trace_span!("my_span", greeting = "hello world", parting = field::Empty);
1180    ///
1181    /// // ...
1182    ///
1183    /// // Now, you try to record a value for a new field, `new_field`, which was not
1184    /// // declared as `Empty` or populated when you created `span`.
1185    /// // You won't get any error, but the assignment will have no effect!
1186    /// span.record("new_field", "interesting_value_you_really_need");
1187    ///
1188    /// // Instead, all fields that may be recorded after span creation should be declared up front,
1189    /// // using field::Empty when a value is not known, as we did for `parting`.
1190    /// // This `record` call will indeed replace field::Empty with "you will be remembered".
1191    /// span.record("parting", "you will be remembered");
1192    /// ```
1193    ///
1194    /// <div class="example-wrap" style="display:inline-block">
1195    /// <pre class="ignore" style="white-space:normal;font:inherit;">
1196    /// **Note**: To record several values in just one call, see the [`record_all!`](crate::record_all!) macro.
1197    /// </pre></div>
1198    ///
1199    /// [`field::Empty`]: super::field::Empty
1200    /// [`Metadata`]: super::Metadata
1201    pub fn record<Q, V>(&self, field: &Q, value: V) -> &Self
1202    where
1203        Q: field::AsField + ?Sized,
1204        V: field::Value,
1205    {
1206        if let Some(meta) = self.meta {
1207            if let Some(field) = field.as_field(meta) {
1208                self.record_all(
1209                    &meta
1210                        .fields()
1211                        .value_set(&[(&field, Some(&value as &dyn field::Value))]),
1212                );
1213            }
1214        }
1215
1216        self
1217    }
1218
1219    /// Records all the fields in the provided `ValueSet`.
1220    #[doc(hidden)]
1221    pub fn record_all(&self, values: &field::ValueSet<'_>) -> &Self {
1222        let record = Record::new(values);
1223        if let Some(ref inner) = self.inner {
1224            inner.record(&record);
1225        }
1226
1227        if let Some(_meta) = self.meta {
1228            if_log_enabled! { *_meta.level(), {
1229                let target = if record.is_empty() {
1230                    LIFECYCLE_LOG_TARGET
1231                } else {
1232                    _meta.target()
1233                };
1234                self.log(
1235                    target,
1236                    level_to_log!(*_meta.level()),
1237                    format_args!("{};{}", _meta.name(), crate::log::LogValueSet { values, is_first: false }),
1238                );
1239            }}
1240        }
1241
1242        self
1243    }
1244
1245    /// Returns `true` if this span was disabled by the collector and does not
1246    /// exist.
1247    ///
1248    /// See also [`is_none`].
1249    ///
1250    /// [`is_none`]: Span::is_none()
1251    #[inline]
1252    pub fn is_disabled(&self) -> bool {
1253        self.inner.is_none()
1254    }
1255
1256    /// Returns `true` if this span was constructed by [`Span::none`] and is
1257    /// empty.
1258    ///
1259    /// If `is_none` returns `true` for a given span, then [`is_disabled`] will
1260    /// also return `true`. However, when a span is disabled by the collector
1261    /// rather than constructed by `Span::none`, this method will return
1262    /// `false`, while `is_disabled` will return `true`.
1263    ///
1264    /// [`is_disabled`]: Span::is_disabled()
1265    #[inline]
1266    pub fn is_none(&self) -> bool {
1267        self.is_disabled() && self.meta.is_none()
1268    }
1269
1270    /// Indicates that the span with the given ID has an indirect causal
1271    /// relationship with this span.
1272    ///
1273    /// This relationship differs somewhat from the parent-child relationship: a
1274    /// span may have any number of prior spans, rather than a single one; and
1275    /// spans are not considered to be executing _inside_ of the spans they
1276    /// follow from. This means that a span may close even if subsequent spans
1277    /// that follow from it are still open, and time spent inside of a
1278    /// subsequent span should not be included in the time its precedents were
1279    /// executing. This is used to model causal relationships such as when a
1280    /// single future spawns several related background tasks, et cetera.
1281    ///
1282    /// If this span is disabled, or the resulting follows-from relationship
1283    /// would be invalid, this function will do nothing.
1284    ///
1285    /// # Examples
1286    ///
1287    /// Setting a `follows_from` relationship with a `Span`:
1288    /// ```
1289    /// # use tracing::{span, Id, Level, Span};
1290    /// let span1 = span!(Level::INFO, "span_1");
1291    /// let span2 = span!(Level::DEBUG, "span_2");
1292    /// span2.follows_from(&span1);
1293    /// ```
1294    ///
1295    /// Setting a `follows_from` relationship with the current span:
1296    /// ```
1297    /// # use tracing::{span, Id, Level, Span};
1298    /// let span = span!(Level::INFO, "hello!");
1299    /// span.follows_from(&Span::current());
1300    /// ```
1301    ///
1302    /// Setting a `follows_from` relationship with an `Id`:
1303    /// ```
1304    /// # use tracing::{span, Id, Level, Span};
1305    /// let span = span!(Level::INFO, "hello!");
1306    /// let id = span.id();
1307    /// span.follows_from(id);
1308    /// ```
1309    pub fn follows_from(&self, from: impl Into<Option<Id>>) -> &Self {
1310        if let Some(ref inner) = self.inner {
1311            if let Some(from) = from.into() {
1312                inner.follows_from(&from);
1313            }
1314        }
1315        self
1316    }
1317
1318    /// Returns this span's `Id`, if it is enabled.
1319    pub fn id(&self) -> Option<Id> {
1320        self.inner.as_ref().map(Inner::id)
1321    }
1322
1323    /// Returns this span's `Metadata`, if it is enabled.
1324    pub fn metadata(&self) -> Option<&'static Metadata<'static>> {
1325        self.meta
1326    }
1327
1328    #[cfg(feature = "log")]
1329    #[inline]
1330    fn log(&self, target: &str, level: log::Level, message: fmt::Arguments<'_>) {
1331        if let Some(meta) = self.meta {
1332            if level_to_log!(*meta.level()) <= log::max_level() {
1333                let logger = log::logger();
1334                let log_meta = log::Metadata::builder().level(level).target(target).build();
1335                if logger.enabled(&log_meta) {
1336                    if let Some(ref inner) = self.inner {
1337                        logger.log(
1338                            &log::Record::builder()
1339                                .metadata(log_meta)
1340                                .module_path(meta.module_path())
1341                                .file(meta.file())
1342                                .line(meta.line())
1343                                .args(format_args!("{} span={}", message, inner.id.into_u64()))
1344                                .build(),
1345                        );
1346                    } else {
1347                        logger.log(
1348                            &log::Record::builder()
1349                                .metadata(log_meta)
1350                                .module_path(meta.module_path())
1351                                .file(meta.file())
1352                                .line(meta.line())
1353                                .args(message)
1354                                .build(),
1355                        );
1356                    }
1357                }
1358            }
1359        }
1360    }
1361
1362    /// Invokes a function with a reference to this span's ID and collector.
1363    ///
1364    /// if this span is enabled, the provided function is called, and the result is returned.
1365    /// If the span is disabled, the function is not called, and this method returns `None`
1366    /// instead.
1367    pub fn with_collector<T>(&self, f: impl FnOnce((&Id, &Dispatch)) -> T) -> Option<T> {
1368        self.inner
1369            .as_ref()
1370            .map(|inner| f((&inner.id, &inner.collector)))
1371    }
1372}
1373
1374impl cmp::PartialEq for Span {
1375    fn eq(&self, other: &Self) -> bool {
1376        match (&self.meta, &other.meta) {
1377            (Some(this), Some(that)) => {
1378                this.callsite() == that.callsite() && self.inner == other.inner
1379            }
1380            _ => false,
1381        }
1382    }
1383}
1384
1385impl Hash for Span {
1386    fn hash<H: Hasher>(&self, hasher: &mut H) {
1387        self.inner.hash(hasher);
1388    }
1389}
1390
1391impl fmt::Debug for Span {
1392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1393        let mut span = f.debug_struct("Span");
1394        if let Some(meta) = self.meta {
1395            span.field("name", &meta.name())
1396                .field("level", &meta.level())
1397                .field("target", &meta.target());
1398
1399            if let Some(ref inner) = self.inner {
1400                span.field("id", &inner.id());
1401            } else {
1402                span.field("disabled", &true);
1403            }
1404
1405            if let Some(ref path) = meta.module_path() {
1406                span.field("module_path", &path);
1407            }
1408
1409            if let Some(ref line) = meta.line() {
1410                span.field("line", &line);
1411            }
1412
1413            if let Some(ref file) = meta.file() {
1414                span.field("file", &file);
1415            }
1416        } else {
1417            span.field("none", &true);
1418        }
1419
1420        span.finish()
1421    }
1422}
1423
1424impl<'a> From<&'a Span> for Option<&'a Id> {
1425    fn from(span: &'a Span) -> Self {
1426        span.inner.as_ref().map(|inner| &inner.id)
1427    }
1428}
1429
1430impl<'a> From<&'a Span> for Option<Id> {
1431    fn from(span: &'a Span) -> Self {
1432        span.inner.as_ref().map(Inner::id)
1433    }
1434}
1435
1436impl<'a> From<&'a EnteredSpan> for Option<&'a Id> {
1437    fn from(span: &'a EnteredSpan) -> Self {
1438        span.inner.as_ref().map(|inner| &inner.id)
1439    }
1440}
1441
1442impl<'a> From<&'a EnteredSpan> for Option<Id> {
1443    fn from(span: &'a EnteredSpan) -> Self {
1444        span.inner.as_ref().map(Inner::id)
1445    }
1446}
1447
1448impl Drop for Span {
1449    #[inline(always)]
1450    fn drop(&mut self) {
1451        if let Some(Inner {
1452            ref id,
1453            ref collector,
1454        }) = self.inner
1455        {
1456            collector.try_close(id.clone());
1457        }
1458
1459        if_log_enabled! { crate::Level::TRACE, {
1460            if let Some(meta) = self.meta {
1461                self.log(
1462                    LIFECYCLE_LOG_TARGET,
1463                    log::Level::Trace,
1464                    format_args!("-- {};", meta.name()),
1465                );
1466            }
1467        }}
1468    }
1469}
1470
1471// ===== impl Inner =====
1472
1473impl Inner {
1474    /// Indicates that the span with the given ID has an indirect causal
1475    /// relationship with this span.
1476    ///
1477    /// This relationship differs somewhat from the parent-child relationship: a
1478    /// span may have any number of prior spans, rather than a single one; and
1479    /// spans are not considered to be executing _inside_ of the spans they
1480    /// follow from. This means that a span may close even if subsequent spans
1481    /// that follow from it are still open, and time spent inside of a
1482    /// subsequent span should not be included in the time its precedents were
1483    /// executing. This is used to model causal relationships such as when a
1484    /// single future spawns several related background tasks, et cetera.
1485    ///
1486    /// If this span is disabled, this function will do nothing. Otherwise, it
1487    /// returns `Ok(())` if the other span was added as a precedent of this
1488    /// span, or an error if this was not possible.
1489    fn follows_from(&self, from: &Id) {
1490        self.collector.record_follows_from(&self.id, from)
1491    }
1492
1493    /// Returns the span's ID.
1494    fn id(&self) -> Id {
1495        self.id.clone()
1496    }
1497
1498    fn record(&self, values: &Record<'_>) {
1499        self.collector.record(&self.id, values)
1500    }
1501
1502    fn new(id: Id, collector: &Dispatch) -> Self {
1503        Inner {
1504            id,
1505            collector: collector.clone(),
1506        }
1507    }
1508}
1509
1510impl cmp::PartialEq for Inner {
1511    fn eq(&self, other: &Self) -> bool {
1512        self.id == other.id
1513    }
1514}
1515
1516impl Hash for Inner {
1517    fn hash<H: Hasher>(&self, state: &mut H) {
1518        self.id.hash(state);
1519    }
1520}
1521
1522impl Clone for Inner {
1523    fn clone(&self) -> Self {
1524        Inner {
1525            id: self.collector.clone_span(&self.id),
1526            collector: self.collector.clone(),
1527        }
1528    }
1529}
1530
1531// ===== impl Entered =====
1532
1533impl EnteredSpan {
1534    /// Returns this span's `Id`, if it is enabled.
1535    pub fn id(&self) -> Option<Id> {
1536        self.inner.as_ref().map(Inner::id)
1537    }
1538
1539    /// Exits this span, returning the underlying [`Span`].
1540    #[inline]
1541    pub fn exit(mut self) -> Span {
1542        // One does not simply move out of a struct with `Drop`.
1543        let span = mem::replace(&mut self.span, Span::none());
1544        span.do_exit();
1545        span
1546    }
1547}
1548
1549impl Deref for EnteredSpan {
1550    type Target = Span;
1551
1552    #[inline]
1553    fn deref(&self) -> &Span {
1554        &self.span
1555    }
1556}
1557
1558impl Drop for Entered<'_> {
1559    #[inline(always)]
1560    fn drop(&mut self) {
1561        self.span.do_exit()
1562    }
1563}
1564
1565impl Drop for EnteredSpan {
1566    #[inline(always)]
1567    fn drop(&mut self) {
1568        self.span.do_exit()
1569    }
1570}
1571
1572/// Technically, `Entered` (or `EnteredSpan`) _can_ implement both `Send` *and*
1573/// `Sync` safely. It doesn't, because it has a `PhantomNotSend` field,
1574/// specifically added in order to make it `!Send`.
1575///
1576/// Sending an `Entered` guard between threads cannot cause memory unsafety.
1577/// However, it *would* result in incorrect behavior, so we add a
1578/// `PhantomNotSend` to prevent it from being sent between threads. This is
1579/// because it must be *dropped* on the same thread that it was created;
1580/// otherwise, the span will never be exited on the thread where it was entered,
1581/// and it will attempt to exit the span on a thread that may never have entered
1582/// it. However, we still want them to be `Sync` so that a struct holding an
1583/// `Entered` guard can be `Sync`.
1584///
1585/// Thus, this is totally safe.
1586#[derive(Debug)]
1587struct PhantomNotSend {
1588    ghost: PhantomData<*mut ()>,
1589}
1590
1591#[allow(non_upper_case_globals)]
1592const PhantomNotSend: PhantomNotSend = PhantomNotSend { ghost: PhantomData };
1593
1594/// # Safety
1595///
1596/// Trivially safe, as `PhantomNotSend` doesn't have any API.
1597unsafe impl Sync for PhantomNotSend {}
1598
1599#[cfg(test)]
1600mod test {
1601    use super::*;
1602
1603    #[allow(dead_code)]
1604    trait AssertSend: Send {}
1605    impl AssertSend for Span {}
1606
1607    #[allow(dead_code)]
1608    trait AssertSync: Sync {}
1609    impl AssertSync for Span {}
1610    impl AssertSync for Entered<'_> {}
1611    impl AssertSync for EnteredSpan {}
1612
1613    #[test]
1614    fn test_record_backwards_compat() {
1615        Span::current().record("some-key", "some text");
1616        Span::current().record("some-key", false);
1617    }
1618}