aedm
aedm

Reputation: 6564

Anyhow context from tracing intrumentation?

I use the anyhow and tracing crates. Tracing provides great context for my logging. Is it possible to use the same context for anyhow's error contexts?

#[instrument()]
fn foo(s: &str) -> Result<i64> {
    let x = s.parse::<i64>().with_context(|| format!("failed to parse `{s}` as integer"))?;
    info!("Parse result: {x}");
    Ok(x + 1)
}

fn main() {
    // initialize tracing_subscriber...

    println!("{:?}", foo("42"));
    println!("{:?}", foo("bar"));
}

The output is:

2024-10-07T16:09:19.156939Z  INFO foo{s="42"}: rust_so: Parse result: 42
Ok(43)
Err(failed to parse `bar` as integer

Caused by:
    invalid digit found in string

Stack backtrace: 
[...]

The foo{s="42"} part is a great thing to see in logs. But the .with_context method ignores it completely, so I have to manually add the arguments to the error message.

How can I connect these two and make foo{s="42"} show up in error contexts? I'm looking for a solution convenient enough to use thoughout my entire app.

Upvotes: 0

Views: 66

Answers (0)

Related Questions