Skip to content

Inherit tracing spans, if the program uses tracing #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,15 @@ log = "0.4.20"
faccess = "0.2.4"
os_pipe = "1.1.4"
env_logger = "0.10.0"
tracing = { version = "0.1.41", optional = true }

[dev-dependencies]
rayon = "1.8.0"
clap = { version = "4", features = ["derive"] }
byte-unit = "4.0.19"
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }

[[example]]
name = "tracing"
required-features = ["tracing"]
27 changes: 27 additions & 0 deletions examples/tracing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use cmd_lib::{run_cmd, CmdResult};
use tracing::level_filters::LevelFilter;
use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, EnvFilter};

#[cmd_lib::main]
fn main() -> CmdResult {
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();

copy_thing()?;

Ok(())
}

#[tracing::instrument]
fn copy_thing() -> CmdResult {
// Log output from stderr inherits the `copy_thing` span from this function
run_cmd!(dd if=/dev/urandom of=/dev/null bs=1M count=1000)?;

Ok(())
}
4 changes: 4 additions & 0 deletions src/child.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,9 +341,13 @@ struct StderrThread {

impl StderrThread {
fn new(cmd: &str, file: &str, line: u32, stderr: Option<PipeReader>, capture: bool) -> Self {
#[cfg(feature = "tracing")]
let span = tracing::Span::current();
if let Some(stderr) = stderr {
let file_ = file.to_owned();
let thread = std::thread::spawn(move || {
#[cfg(feature = "tracing")]
let _entered = span.enter();
if capture {
let mut output = String::new();
BufReader::new(stderr)
Expand Down