This is the method I'd like to call: pub fn current().
I just follow the crates' documentation, and following is an example I came up with, which does some logging to hourly rolling log file.
Content of Cargo.toml:
[package]
name = "learn-tracing-log"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
time = { version = "0.3.22", default-features = false, features = ["formatting", "macros", "parsing"] }
tracing = "0.1.40"
tracing-appender = "0.2.2"
tracing-subscriber = {version = "0.3.17", features = ["fmt", "std", "local-time", "time"]}
rand = "0.8.5"
Content of src/main.rs:
use time::macros::format_description;
use tracing::Level;
use tracing_subscriber::fmt::time::LocalTime;
use std::io;
use rand::Rng;
fn main() {
let file_appender = tracing_appender::rolling::hourly("./", "prefix.log");
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
let tracing_sub = tracing_subscriber::fmt();
//tracing_subscriber::fmt()
tracing_sub
.with_writer(non_blocking)
//.with_max_level(Level::TRACE) //ERROR, WARN, INFO, DEBUG, TRACE
//.with_max_level(Level::DEBUG) //ERROR, WARN, INFO, DEBUG
.with_max_level(Level::INFO) //ERROR, WARN, INFO
.with_timer(LocalTime::new(format_description!("[hour]:[minute]:[second]")))
.with_ansi(false)
.init();
tracing::info!("Initialisation completed.");
// TO_DO: how to call pub fn current()?
// How to get to the active Subscriber?
// tracing::info!("tracing_subscriber.current() {}", tracing_sub.???.current());
loop {
println!("Please type in something: ");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let trimmed_input = input.trim();
match rand::thread_rng().gen_range(1..=5) {
1 => tracing::info!("You typed in: {trimmed_input}"),
2 => tracing::debug!("You typed in: {trimmed_input}"),
3 => tracing::warn!("You typed in: {trimmed_input}"),
4 => tracing::error!("You typed in: {trimmed_input}"),
5 => tracing::trace!("You typed in: {trimmed_input}"),
_ => tracing::info!("_: {trimmed_input}"),
}
}
}
Thank you and best regards,
...behai.