Created
July 9, 2020 02:01
-
-
Save yaahc/b9c372d7b567bd1edc986d4054e1de30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tracing_futures::Instrument; | |
pub struct FancyGuard<'a> { | |
span: &'a tracing::Span, | |
entered: bool, | |
} | |
impl<'a> FancyGuard<'a> { | |
pub fn new(span: &'a tracing::Span) -> FancyGuard<'a> { | |
span.with_subscriber(|(id, sub)| sub.enter(id)).unwrap(); | |
Self { | |
span, | |
entered: true, | |
} | |
} | |
pub async fn wrap<F>(&mut self, fut: F) -> F::Output | |
where | |
F: std::future::Future, | |
{ | |
self.span.with_subscriber(|(id, sub)| sub.exit(id)).unwrap(); | |
self.entered = false; | |
let output = fut.instrument(self.span.clone()).await; | |
self.span | |
.with_subscriber(|(id, sub)| sub.enter(id)) | |
.unwrap(); | |
self.entered = true; | |
output | |
} | |
} | |
impl Drop for FancyGuard<'_> { | |
fn drop(&mut self) { | |
if self.entered { | |
self.span.with_subscriber(|(id, sub)| sub.exit(id)).unwrap(); | |
} | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
async fn test() -> Result<(), ()> { | |
tracing::error!( | |
"event in wrapped future, shouldn't include fancy span and should include boo hoo" | |
); | |
Ok(()) | |
} | |
#[tokio::test] | |
async fn it_works() { | |
tracing_subscriber::fmt::init(); | |
let span = tracing::error_span!("fancy span"); | |
tracing::error!("outside of fancy guard"); | |
let mut guard = FancyGuard::new(&span); | |
tracing::error!("inside of fancy guard"); | |
guard | |
.wrap({ | |
tracing::error!("this should happen inside of fancy guard"); | |
test() | |
}) | |
.await | |
.map(|()| tracing::error!("back in fancy guard")) | |
.unwrap_err(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment