Struct kernel::serial_trace::Span

source ·
pub struct Span {
    inner: Option<Inner>,
    meta: Option<&'static Metadata<'static>>,
}
Expand description

A handle representing a span, with the capability to enter the span if it exists.

If the span was rejected by the current Subscriber’s filter, entering the span will silently do nothing. Thus, the handle can be used in the same manner regardless of whether or not the trace is currently being collected.

Fields§

§inner: Option<Inner>§meta: Option<&'static Metadata<'static>>

Implementations§

source§

impl Span

source

pub fn new(meta: &'static Metadata<'static>, values: &ValueSet<'_>) -> Span

Constructs a new Span with the given metadata and set of field values.

The new span will be constructed by the currently-active Subscriber, with the current span as its parent (if one exists).

After the span is constructed, field values and/or follows_from annotations may be added to it.

source

pub fn new_root(meta: &'static Metadata<'static>, values: &ValueSet<'_>) -> Span

Constructs a new Span as the root of its own trace tree, with the given metadata and set of field values.

After the span is constructed, field values and/or follows_from annotations may be added to it.

source

pub fn child_of( parent: impl Into<Option<Id>>, meta: &'static Metadata<'static>, values: &ValueSet<'_>, ) -> Span

Constructs a new Span as child of the given parent span, with the given metadata and set of field values.

After the span is constructed, field values and/or follows_from annotations may be added to it.

source

pub fn new_disabled(meta: &'static Metadata<'static>) -> Span

Constructs a new disabled span with the given Metadata.

This should be used when a span is constructed from a known callsite, but the subscriber indicates that it is disabled.

Entering, exiting, and recording values on this span will not notify the Subscriber but may record log messages if the log feature flag is enabled.

source

pub const fn none() -> Span

Constructs a new span that is completely disabled.

This can be used rather than Option<Span> to represent cases where a span is not present.

Entering, exiting, and recording values on this span will do nothing.

source

pub fn current() -> Span

Returns a handle to the span considered by the Subscriber to be the current span.

If the subscriber indicates that it does not track the current span, or that the thread from which this function is called is not currently inside a span, the returned span will be disabled.

source

pub fn enter(&self) -> Entered<'_>

Enters this span, returning a guard that will exit the span when dropped.

If this span is enabled by the current subscriber, then this function will call Subscriber::enter with the span’s Id, and dropping the guard will call Subscriber::exit. If the span is disabled, this does nothing.

§In Asynchronous Code

Warning: in asynchronous code that uses async/await syntax, Span::enter should be used very carefully or avoided entirely. Holding the drop guard returned by Span::enter across .await points will result in incorrect traces. For example,

async fn my_async_function() {
    let span = info_span!("my_async_function");

    // WARNING: This span will remain entered until this
    // guard is dropped...
    let _enter = span.enter();
    // ...but the `await` keyword may yield, causing the
    // runtime to switch to another task, while remaining in
    // this span!
    some_other_async_function().await

    // ...
}

The drop guard returned by Span::enter exits the span when it is dropped. When an async function or async block yields at an .await point, the current scope is exited, but values in that scope are not dropped (because the async block will eventually resume execution from that await point). This means that another task will begin executing while remaining in the entered span. This results in an incorrect trace.

Instead of using Span::enter in asynchronous code, prefer the following:

  • To enter a span for a synchronous section of code within an async block or function, prefer Span::in_scope. Since in_scope takes a synchronous closure and exits the span when the closure returns, the span will always be exited before the next await point. For example:

    async fn my_async_function() {
        let span = info_span!("my_async_function");
    
        let some_value = span.in_scope(|| {
            // run some synchronous code inside the span...
        });
    
        // This is okay! The span has already been exited before we reach
        // the await point.
        some_other_async_function(some_value).await;
    
        // ...
    }
  • For instrumenting asynchronous code, tracing provides the Future::instrument combinator for attaching a span to a future (async function or block). This will enter the span every time the future is polled, and exit it whenever the future yields.

    Instrument can be used with an async block inside an async function:

    use tracing::Instrument;
    
    async fn my_async_function() {
        let span = info_span!("my_async_function");
        async move {
           // This is correct! If we yield here, the span will be exited,
           // and re-entered when we resume.
           some_other_async_function().await;
    
           //more asynchronous code inside the span...
    
        }
          // instrument the async block with the span...
          .instrument(span)
          // ...and await it.
          .await
    }

    It can also be used to instrument calls to async functions at the callsite:

    use tracing::Instrument;
    
    async fn my_async_function() {
        let some_value = some_other_async_function()
           .instrument(debug_span!("some_other_async_function"))
           .await;
    
        // ...
    }
  • The #[instrument] attribute macro can automatically generate correct code when used on an async function:

    #[tracing::instrument(level = "info")]
    async fn my_async_function() {
    
        // This is correct! If we yield here, the span will be exited,
        // and re-entered when we resume.
        some_other_async_function().await;
    
        // ...
    
    }
§Examples
let span = span!(Level::INFO, "my_span");
let guard = span.enter();

// code here is within the span

drop(guard);

// code here is no longer within the span

Guards need not be explicitly dropped:

fn my_function() -> String {
    // enter a span for the duration of this function.
    let span = trace_span!("my_function");
    let _enter = span.enter();

    // anything happening in functions we call is still inside the span...
    my_other_function();

    // returning from the function drops the guard, exiting the span.
    return "Hello world".to_owned();
}

fn my_other_function() {
    // ...
}

Sub-scopes may be created to limit the duration for which the span is entered:

let span = info_span!("my_great_span");

{
    let _enter = span.enter();

    // this event occurs inside the span.
    info!("i'm in the span!");

    // exiting the scope drops the guard, exiting the span.
}

// this event is not inside the span.
info!("i'm outside the span!")
source

pub fn entered(self) -> EnteredSpan

Enters this span, consuming it and returning a guard that will exit the span when dropped.

    Warning: In asynchronous code that uses async/await syntax,
    Span::entered may produce incorrect traces if the returned drop
    guard is held across an await point. See the
    Span::enter documentation for details.

If this span is enabled by the current subscriber, then this function will call Subscriber::enter with the span’s Id, and dropping the guard will call Subscriber::exit. If the span is disabled, this does nothing.

This is similar to the Span::enter method, except that it moves the span by value into the returned guard, rather than borrowing it. Therefore, this method can be used to create and enter a span in a single expression, without requiring a let-binding. For example:

let _span = info_span!("something_interesting").entered();

rather than:

let span = info_span!("something_interesting");
let _e = span.enter();

Furthermore, entered may be used when the span must be stored in some other struct or be passed to a function while remaining entered.

    Note: The returned 
    EnteredSpan guard does not implement Send.
    Dropping the guard will exit this span, and if the guard is sent
    to another thread and dropped there, that thread may never have entered
    this span. Thus, EnteredSpans should not be sent between threads.
§Examples

The returned guard can be explicitly exited, returning the un-entered span:

let span = span!(Level::INFO, "doing_something").entered();

// code here is within the span

// explicitly exit the span, returning it
let span = span.exit();

// code here is no longer within the span

// enter the span again
let span = span.entered();

// now we are inside the span once again

Guards need not be explicitly dropped:

fn my_function() -> String {
    // enter a span for the duration of this function.
    let span = trace_span!("my_function").entered();

    // anything happening in functions we call is still inside the span...
    my_other_function();

    // returning from the function drops the guard, exiting the span.
    return "Hello world".to_owned();
}

fn my_other_function() {
    // ...
}

Since the EnteredSpan guard can dereference to the Span itself, the span may still be accessed while entered. For example:

use tracing::field;

// create the span with an empty field, and enter it.
let span = info_span!("my_span", some_field = field::Empty).entered();

// we can still record a value for the field while the span is entered.
span.record("some_field", &"hello world!");
source

pub fn or_current(self) -> Span

Returns this span, if it was enabled by the current Subscriber, or the current span (whose lexical distance may be further than expected), if this span is disabled.

This method can be useful when propagating spans to spawned threads or async tasks. Consider the following:

let _parent_span = tracing::info_span!("parent").entered();

// ...

let child_span = tracing::debug_span!("child");

std::thread::spawn(move || {
    let _entered = child_span.entered();

    tracing::info!("spawned a thread!");

    // ...
});

If the current Subscriber enables the DEBUG level, then both the “parent” and “child” spans will be enabled. Thus, when the “spawaned a thread!” event occurs, it will be inside of the “child” span. Because “parent” is the parent of “child”, the event will also be inside of “parent”.

However, if the Subscriber only enables the INFO level, the “child” span will be disabled. When the thread is spawned, the child_span.entered() call will do nothing, since “child” is not enabled. In this case, the “spawned a thread!” event occurs outside of any span, since the “child” span was responsible for propagating its parent to the spawned thread.

If this is not the desired behavior, Span::or_current can be used to ensure that the “parent” span is propagated in both cases, either as a parent of “child” or directly. For example:

let _parent_span = tracing::info_span!("parent").entered();

// ...

// If DEBUG is enabled, then "child" will be enabled, and `or_current`
// returns "child". Otherwise, if DEBUG is not enabled, "child" will be
// disabled, and `or_current` returns "parent".
let child_span = tracing::debug_span!("child").or_current();

std::thread::spawn(move || {
    let _entered = child_span.entered();

    tracing::info!("spawned a thread!");

    // ...
});

When spawning asynchronous tasks, Span::or_current can be used similarly, in combination with instrument:

use tracing::Instrument;

let _parent_span = tracing::info_span!("parent").entered();

// ...

let child_span = tracing::debug_span!("child");

tokio::spawn(
    async {
        tracing::info!("spawned a task!");

        // ...

    }.instrument(child_span.or_current())
);

In general, or_current should be preferred over nesting an instrument call inside of an in_current_span call, as using or_current will be more efficient.

use tracing::Instrument;
async fn my_async_fn() {
    // ...
}

let _parent_span = tracing::info_span!("parent").entered();

// Do this:
tokio::spawn(
    my_async_fn().instrument(tracing::debug_span!("child").or_current())
);

// ...rather than this:
tokio::spawn(
    my_async_fn()
        .instrument(tracing::debug_span!("child"))
        .in_current_span()
);
source

pub fn in_scope<F, T>(&self, f: F) -> T
where F: FnOnce() -> T,

Executes the given function in the context of this span.

If this span is enabled, then this function enters the span, invokes f and then exits the span. If the span is disabled, f will still be invoked, but in the context of the currently-executing span (if there is one).

Returns the result of evaluating f.

§Examples
let my_span = span!(Level::TRACE, "my_span");

my_span.in_scope(|| {
    // this event occurs within the span.
    trace!("i'm in the span!");
});

// this event occurs outside the span.
trace!("i'm not in the span!");

Calling a function and returning the result:

fn hello_world() -> String {
    "Hello world!".to_owned()
}

let span = info_span!("hello_world");
// the span will be entered for the duration of the call to
// `hello_world`.
let a_string = span.in_scope(hello_world);
source

pub fn field<Q>(&self, field: &Q) -> Option<Field>
where Q: AsField + ?Sized,

Returns a Field for the field with the given name, if one exists,

source

pub fn has_field<Q>(&self, field: &Q) -> bool
where Q: AsField + ?Sized,

Returns true if this Span has a field for the given Field or field name.

source

pub fn record<Q, V>(&self, field: &Q, value: V) -> &Span
where Q: AsField + ?Sized, V: Value,

Records that the field described by field has the value value.

This may be used with field::Empty to declare fields whose values are not known when the span is created, and record them later:

use tracing::{trace_span, field};

// Create a span with two fields: `greeting`, with the value "hello world", and
// `parting`, without a value.
let span = trace_span!("my_span", greeting = "hello world", parting = field::Empty);

// ...

// Now, record a value for parting as well.
// (note that the field name is passed as a string slice)
span.record("parting", "goodbye world!");

However, it may also be used to record a new value for a field whose value was already recorded:

use tracing::info_span;

// Initially, let's assume that our attempt to do something is going okay...
let span = info_span!("doing_something", is_okay = true);
let _e = span.enter();

match do_something() {
    Ok(something) => {
        // ...
    }
    Err(_) => {
        // Things are no longer okay!
        span.record("is_okay", false);
    }
}
    Note: The fields associated with a span are part
    of its Metadata.
    The Metadata
    describing a particular span is constructed statically when the span
    is created and cannot be extended later to add new fields. Therefore,
    you cannot record a value for a field that was not specified when the
    span was created:
use tracing::{trace_span, field};

// Create a span with two fields: `greeting`, with the value "hello world", and
// `parting`, without a value.
let span = trace_span!("my_span", greeting = "hello world", parting = field::Empty);

// ...

// Now, you try to record a value for a new field, `new_field`, which was not
// declared as `Empty` or populated when you created `span`.
// You won't get any error, but the assignment will have no effect!
span.record("new_field", "interesting_value_you_really_need");

// Instead, all fields that may be recorded after span creation should be declared up front,
// using field::Empty when a value is not known, as we did for `parting`.
// This `record` call will indeed replace field::Empty with "you will be remembered".
span.record("parting", "you will be remembered");
source

pub fn record_all(&self, values: &ValueSet<'_>) -> &Span

Records all the fields in the provided ValueSet.

source

pub fn is_disabled(&self) -> bool

Returns true if this span was disabled by the subscriber and does not exist.

See also is_none.

source

pub fn is_none(&self) -> bool

Returns true if this span was constructed by Span::none and is empty.

If is_none returns true for a given span, then is_disabled will also return true. However, when a span is disabled by the subscriber rather than constructed by Span::none, this method will return false, while is_disabled will return true.

source

pub fn follows_from(&self, from: impl Into<Option<Id>>) -> &Span

Indicates that the span with the given ID has an indirect causal relationship with this span.

This relationship differs somewhat from the parent-child relationship: a span may have any number of prior spans, rather than a single one; and spans are not considered to be executing inside of the spans they follow from. This means that a span may close even if subsequent spans that follow from it are still open, and time spent inside of a subsequent span should not be included in the time its precedents were executing. This is used to model causal relationships such as when a single future spawns several related background tasks, et cetera.

If this span is disabled, or the resulting follows-from relationship would be invalid, this function will do nothing.

§Examples

Setting a follows_from relationship with a Span:

let span1 = span!(Level::INFO, "span_1");
let span2 = span!(Level::DEBUG, "span_2");
span2.follows_from(span1);

Setting a follows_from relationship with the current span:

let span = span!(Level::INFO, "hello!");
span.follows_from(Span::current());

Setting a follows_from relationship with a Span reference:

let span = span!(Level::INFO, "hello!");
let curr = Span::current();
span.follows_from(&curr);

Setting a follows_from relationship with an Id:

let span = span!(Level::INFO, "hello!");
let id = span.id();
span.follows_from(id);
source

pub fn id(&self) -> Option<Id>

Returns this span’s Id, if it is enabled.

source

pub fn metadata(&self) -> Option<&'static Metadata<'static>>

Returns this span’s Metadata, if it is enabled.

source

pub fn with_subscriber<T>( &self, f: impl FnOnce((&Id, &Dispatch)) -> T, ) -> Option<T>

Invokes a function with a reference to this span’s ID and subscriber.

if this span is enabled, the provided function is called, and the result is returned. If the span is disabled, the function is not called, and this method returns None instead.

Trait Implementations§

source§

impl Clone for Span

source§

fn clone(&self) -> Span

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Span

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Drop for Span

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl Hash for Span

source§

fn hash<H>(&self, hasher: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for Span

source§

fn eq(&self, other: &Span) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl Freeze for Span

§

impl !RefUnwindSafe for Span

§

impl Send for Span

§

impl Sync for Span

§

impl Unpin for Span

§

impl !UnwindSafe for Span

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Az for T

source§

fn az<Dst>(self) -> Dst
where T: Cast<Dst>,

Casts the value.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<Src, Dst> CastFrom<Src> for Dst
where Src: Cast<Dst>,

source§

fn cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> CheckedAs for T

source§

fn checked_as<Dst>(self) -> Option<Dst>
where T: CheckedCast<Dst>,

Casts the value.
source§

impl<Src, Dst> CheckedCastFrom<Src> for Dst
where Src: CheckedCast<Dst>,

source§

fn checked_cast_from(src: Src) -> Option<Dst>

Casts the value.
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> OverflowingAs for T

source§

fn overflowing_as<Dst>(self) -> (Dst, bool)
where T: OverflowingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> OverflowingCastFrom<Src> for Dst
where Src: OverflowingCast<Dst>,

source§

fn overflowing_cast_from(src: Src) -> (Dst, bool)

Casts the value.
source§

impl<T> SaturatingAs for T

source§

fn saturating_as<Dst>(self) -> Dst
where T: SaturatingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> SaturatingCastFrom<Src> for Dst
where Src: SaturatingCast<Dst>,

source§

fn saturating_cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> UnwrappedAs for T

source§

fn unwrapped_as<Dst>(self) -> Dst
where T: UnwrappedCast<Dst>,

Casts the value.
source§

impl<Src, Dst> UnwrappedCastFrom<Src> for Dst
where Src: UnwrappedCast<Dst>,

source§

fn unwrapped_cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> WrappingAs for T

source§

fn wrapping_as<Dst>(self) -> Dst
where T: WrappingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> WrappingCastFrom<Src> for Dst
where Src: WrappingCast<Dst>,

source§

fn wrapping_cast_from(src: Src) -> Dst

Casts the value.