Skip to content

Instantly share code, notes, and snippets.

@haydenbr
Created September 8, 2023 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haydenbr/38269060057d969f9ab4baed49ebdca6 to your computer and use it in GitHub Desktop.
Save haydenbr/38269060057d969f9ab4baed49ebdca6 to your computer and use it in GitHub Desktop.
Tracing Threads
use std::{thread, time::Duration, sync::Arc};
use tracing::{info_span, info, span};
use tracing_subscriber::EnvFilter;
use uuid::Uuid;
use dotenv::dotenv;
fn main() {
dotenv().ok();
tracing_subscriber::fmt()
.with_line_number(true)
.with_file(true)
// we can set the log level output via RUST_LOG env variable
.with_env_filter(EnvFilter::from_default_env())
.json()
.flatten_event(true)
.init();
let req_id = Uuid::new_v4();
let stream_id = Uuid::new_v4();
let replay_type: u8 = 2;
let span = info_span!(
"root",
req_id = req_id.to_string(),
stream_id = stream_id.to_string(),
replay_type,
).entered();
let child_span = Arc::new(info_span!("child_span"));
info!("start");
let t1_span = child_span.clone();
let t1_handle = thread::spawn(move|| {
let _child_span = t1_span.enter();
info!("started thread 1");
thread::sleep(Duration::from_secs(1));
info!("ending thread 1");
});
let t2_span = child_span.clone();
let t2_handle = thread::spawn(move|| {
let _child_span = t2_span.enter();
info!("started thread 2");
thread::sleep(Duration::from_secs(1));
info!("ending thread 2");
});
t1_handle.join().unwrap();
t2_handle.join().unwrap();
let t3_span = child_span.clone();
let t3_handle = thread::spawn(move|| {
let _child_span = t3_span.enter();
info!("started thread 3");
thread::sleep(Duration::from_secs(1));
info_span!("thread_span").in_scope(|| {
info!("started thread span");
thread::sleep(Duration::from_secs(1));
info!("ending thread span");
});
info!("ending thread 3");
});
t3_handle.join().unwrap();
info!("end");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment