Skip to content

Commit f0c102c

Browse files
authored
Merge pull request #80 from delan/tracing
Inherit tracing spans, if the program uses tracing
2 parents a72b039 + b79579a commit f0c102c

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

Cargo.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,15 @@ log = "0.4.20"
2222
faccess = "0.2.4"
2323
os_pipe = "1.1.4"
2424
env_logger = "0.10.0"
25+
tracing = { version = "0.1.41", optional = true }
2526

2627
[dev-dependencies]
2728
rayon = "1.8.0"
2829
clap = { version = "4", features = ["derive"] }
2930
byte-unit = "4.0.19"
31+
tracing = "0.1.41"
32+
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
33+
34+
[[example]]
35+
name = "tracing"
36+
required-features = ["tracing"]

examples/tracing.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
use cmd_lib::{run_cmd, CmdResult};
2+
use tracing::level_filters::LevelFilter;
3+
use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, EnvFilter};
4+
5+
#[cmd_lib::main]
6+
fn main() -> CmdResult {
7+
tracing_subscriber::registry()
8+
.with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
9+
.with(
10+
EnvFilter::builder()
11+
.with_default_directive(LevelFilter::INFO.into())
12+
.from_env_lossy(),
13+
)
14+
.init();
15+
16+
copy_thing()?;
17+
18+
Ok(())
19+
}
20+
21+
#[tracing::instrument]
22+
fn copy_thing() -> CmdResult {
23+
// Log output from stderr inherits the `copy_thing` span from this function
24+
run_cmd!(dd if=/dev/urandom of=/dev/null bs=1M count=1000)?;
25+
26+
Ok(())
27+
}

src/child.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,9 +341,13 @@ struct StderrThread {
341341

342342
impl StderrThread {
343343
fn new(cmd: &str, file: &str, line: u32, stderr: Option<PipeReader>, capture: bool) -> Self {
344+
#[cfg(feature = "tracing")]
345+
let span = tracing::Span::current();
344346
if let Some(stderr) = stderr {
345347
let file_ = file.to_owned();
346348
let thread = std::thread::spawn(move || {
349+
#[cfg(feature = "tracing")]
350+
let _entered = span.enter();
347351
if capture {
348352
let mut output = String::new();
349353
BufReader::new(stderr)

0 commit comments

Comments
 (0)