diff --git a/Cargo.toml b/Cargo.toml index 2909856..1d250f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] diff --git a/examples/tracing.rs b/examples/tracing.rs new file mode 100644 index 0000000..29fa5d5 --- /dev/null +++ b/examples/tracing.rs @@ -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(()) +} diff --git a/src/child.rs b/src/child.rs index 95b7d29..6e4f73d 100644 --- a/src/child.rs +++ b/src/child.rs @@ -341,9 +341,13 @@ struct StderrThread { impl StderrThread { fn new(cmd: &str, file: &str, line: u32, stderr: Option, 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)