tracing

Trait Instrument

Source
pub trait Instrument: Sized {
    // Provided methods
    fn instrument(self, span: Span) -> Instrumented<Self>  { ... }
    fn in_current_span(self) -> Instrumented<Self>  { ... }
}
Expand description

Attaches spans to a [std::future::Future].

Extension trait allowing futures to be instrumented with a tracing span.

Provided Methods§

Source

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

Instruments this type with the provided Span, returning an Instrumented wrapper.

The attached Span will be entered every time the instrumented Future is polled or Dropped.

§Examples

Instrumenting a future:

use tracing::Instrument;

let my_future = async {
    // ...
};

my_future
    .instrument(tracing::info_span!("my_future"))
    .await

The Span::or_current combinator can be used in combination with instrument to ensure that the current span is attached to the future if the span passed to instrument is disabled:

use tracing::Instrument;

let my_future = async {
    // ...
};

let outer_span = tracing::info_span!("outer").entered();

// If the "my_future" span is enabled, then the spawned task will
// be within both "my_future" *and* "outer", since "outer" is
// "my_future"'s parent. However, if "my_future" is disabled,
// the spawned task will *not* be in any span.
tokio::spawn(
    my_future
        .instrument(tracing::debug_span!("my_future"))
);

// Using `Span::or_current` ensures the spawned task is instrumented
// with the current span, if the new span passed to `instrument` is
// not enabled. This means that if the "my_future"  span is disabled,
// the spawned task will still be instrumented with the "outer" span:
tokio::spawn(
   my_future
        .instrument(tracing::debug_span!("my_future").or_current())
);
Source

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper.

The attached Span will be entered every time the instrumented Future is polled or Dropped.

This can be used to propagate the current span when spawning a new future.

§Examples
use tracing::Instrument;

let span = tracing::info_span!("my_span");
let _enter = span.enter();

// ...

let future = async {
    tracing::debug!("this event will occur inside `my_span`");
    // ...
};
tokio::spawn(future.in_current_span());

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: Sized> Instrument for T