-
When a task is spawned, does it inherit the current tracing span? I don't see this called out in the docs, nor am I able to easily figure it out by reading the tokio source code. I (think that I) want this behavior, because I want to be able to associate spawned tasks with the original operations with which they were meant to help. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Tasks don't inherit the current use tracing::Instrument;
tokio::spawn(my_task().in_current_span());
// which is equivalent to
tokio::spawn(my_task().instrument(tracing::Span::current()); Alternatively, if you instrument the spawned future with a new span, that span will have the current span as its parent, so that task will be conceptually "inside" the current span: use tracing::{Instrument, info_span};
// creates a new span called `my_task`, which is a child of the current span, and
// attaches it to the spawned future.
tokio::spawn(my_task().instrument(info_span!("my_task")); Finally, if you want a spawned task to inherit the current task's span if the child span is not enabled by filtering, you can use use tracing::{Instrument, info_span};
// creates a new span called `my_task`, which is a child of the current span:
let span = info_span!("my_task")
// if the child span is not enabled by the `tracing` subscriber, use the
// current span, instead:
.or_current();
tokio::spawn(my_task().instrument(span)); |
Beta Was this translation helpful? Give feedback.
Tasks don't inherit the current
tracing
span unless the current span is explicitly propagated to the spawned task. For example, if you want to spawn a task in the same span as the context in which it's spawned, you can useInstrument::in_current_span
:Alternatively, if you instrument the spawned future with a new span, that span will have the current span as its parent, so that task will be conceptually "inside" the current span: