#tokio #tracing #async #rust

tracing-tools

Quick and simple band aid for instrumenting async code with tracing

7 releases (breaking)

0.6.0 Dec 4, 2021
0.5.0 Jun 19, 2021
0.4.0 Jun 19, 2021
0.3.0 Jun 19, 2021
0.1.1 May 26, 2021

#6 in #async-rust

Download history 25/week @ 2023-02-01 13/week @ 2023-02-08 31/week @ 2023-02-15 115/week @ 2023-02-22 10/week @ 2023-03-01 12/week @ 2023-03-08 11/week @ 2023-03-15 7/week @ 2023-03-22 23/week @ 2023-03-29 9/week @ 2023-04-05 11/week @ 2023-04-12 10/week @ 2023-04-19 17/week @ 2023-04-26 18/week @ 2023-05-03 19/week @ 2023-05-10 6/week @ 2023-05-17

62 downloads per month
Used in 2 crates

MIT license

34KB
93 lines

tracing-tools - tiny lib for easier integration with tracing

Right now tracing is a bit unusable with async code, because recommended way to instrument async code is by using #instrument macro which

  • does not support error formatting(very painful when using together with crates such as anyhow as it will swallow error chain)
  • has very tiresome syntax for skipping fields and by default tries to expose all of them which is completely pointless in 95% of my use cases

So this tiny crate tries to resolve those issues by switching to direct code instrumentation, example:

example

use anyhow::{anyhow, Context};
use tracing::{Level};
use tracing_tools::{span, TracingTask, PinnedFut};
use tokio::time::{sleep, Duration};

type Result<T> = anyhow::Result<T>;

struct Test {
}

impl Test {
    fn drink_coffee(&self, ) -> Result<()> {
        Err(anyhow!("out of coffee"))
    }

    fn fn1(&self, n: usize) -> PinnedFut<'_> {
        TracingTask::new(span!(Level::INFO, n=n, another_field="bow wow!"), async move {
            sleep(Duration::from_secs(1)).await;
            Ok(())
        }).instrument()
    }
    fn fn2(&self, n: usize) -> PinnedFut<'_> {
        TracingTask::new(span!(Level::INFO, n=n, another_field="bow wow!"), async move {
            Ok(self.drink_coffee().context("cannot drink coffee")?)
        }).instrument()
    }
    fn fn3(& self, n: usize) -> PinnedFut<'_> {
        TracingTask::new_short_lived(span!(Level::INFO, n=n, another_field="bow wow!"), async move {
            Ok(self.drink_coffee().context("cannot drink coffee")?)
        }).instrument()
    }
}

fn configure_tracing() -> Result<()>{
    let collector = tracing_subscriber::fmt()
        .with_target(false)
        .with_max_level(Level::INFO)
        .finish();
    tracing::subscriber::set_global_default(collector)?;
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    configure_tracing()?;
    let s = Test {};
    let _ = s.fn1(1).await;
    let _ = s.fn2(2).await;
    let _ = s.fn3(3).await;
    Ok(())
}

Feel free to fork ;)

Dependencies

~585KB