Skip to content

Instantly share code, notes, and snippets.

@flaub
Created October 19, 2022 22:20
Show Gist options
  • Save flaub/f86675534343aafe86b4e4ed6f7844ba to your computer and use it in GitHub Desktop.
Save flaub/f86675534343aafe86b4e4ed6f7844ba to your computer and use it in GitHub Desktop.
ProfLayer
use std::time::{Duration, Instant};
use tracing_core::{span, subscriber::Subscriber};
use tracing_subscriber::{
fmt::{self, format::FmtSpan},
layer::Context,
prelude::*,
registry::LookupSpan,
EnvFilter, Layer,
};
struct ProfLayer {}
struct Timings {
idle: Duration,
busy: Duration,
last: Instant,
}
impl Timings {
fn new() -> Self {
Self {
idle: Duration::ZERO,
busy: Duration::ZERO,
last: Instant::now(),
}
}
}
impl<S> Layer<S> for ProfLayer
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("Span not found, this is a bug");
let mut extensions = span.extensions_mut();
if let Some(timings) = extensions.get_mut::<Timings>() {
let now = Instant::now();
timings.idle += now - timings.last;
timings.last = now;
}
}
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("Span not found, this is a bug");
let mut extensions = span.extensions_mut();
if let Some(timings) = extensions.get_mut::<Timings>() {
let now = Instant::now();
timings.busy += now - timings.last;
timings.last = now;
}
}
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("Span not found, this is a bug");
let extensions = span.extensions();
if let Some(timing) = extensions.get::<Timings>() {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment