This repository has been archived on 2026-03-27. You can view files and clone it, but you cannot make any changes to its state, such as pushing and creating new issues, pull requests or comments.
tracing/examples/examples/thread-info.rs
Hayden Stainsby bdbaf80073
examples: add note to examples that they are for tracing 0.2.0 (#3099)
It is not uncommon that users who are new to tracing look at the
examples in the `master` branch of the repository and find that they
don't compile. This is because they are examples which compile with the
code from the master branch, which is for the as yet unreleased tracing
0.2.0 ecosystem.

Users should instead go to the `v0.1.x` branch to find examples
compatible with the crates published on crates.io.

This change adds a doc-comment to the beginning of every example file
informing the user of this fact and suggesting that they check out the
`v0.1.x` branch instead.
2024-10-09 15:31:11 -04:00

58 lines
1.8 KiB
Rust

//! NOTE: This is pre-release documentation for the upcoming tracing 0.2.0 ecosystem. For the
//! release examples, please see the `v0.1.x` branch instead.
//!
//! This is a example showing how thread info can be displayed when
//! formatting events with `tracing_subscriber::fmt`. This is useful
//! as `tracing` spans can be entered by multiple threads concurrently,
//! or move across threads freely.
//!
//! You can run this example by running the following command in a terminal
//!
//! ```
//! cargo run --example thread-info
//! ```
//!
//! Example output:
//!
//! ```not_rust
//! Jul 17 00:38:07.177 INFO ThreadId(02) thread_info: i=9
//! Jul 17 00:38:07.177 INFO thread 1 ThreadId(03) thread_info: i=9
//! Jul 17 00:38:07.177 INFO large name thread 2 ThreadId(04) thread_info: i=9
//! ```
#![deny(rust_2018_idioms)]
use std::thread;
use std::time::Duration;
use tracing::info;
fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
// enable thread id to be emitted
.with_thread_ids(true)
// enabled thread name to be emitted
.with_thread_names(true)
.init();
let do_work = || {
for i in 1..10 {
info!(i);
thread::sleep(Duration::from_millis(1));
}
};
let thread_with_no_name = thread::spawn(do_work);
let thread_one = thread::Builder::new()
.name("thread 1".to_string())
.spawn(do_work)
.expect("could not spawn a new thread");
let thread_two = thread::Builder::new()
.name("large name thread 2".to_string())
.spawn(do_work)
.expect("could not spawn a new thread");
thread_with_no_name
.join()
.expect("could not wait for a thread");
thread_one.join().expect("could not wait for a thread");
thread_two.join().expect("could not wait for a thread");
}