There is a problem, I need some help!! Why message not log to file?
use std::io;
use std::path::PathBuf;
use time::format_description::FormatItem;
use time::{format_description, UtcOffset};
use tracing::{error, info, instrument, trace};
use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};
use tracing_subscriber::fmt::writer::MakeWriterExt;
use tracing_subscriber::{
fmt::{time::OffsetTime, Layer},
layer::SubscriberExt,
EnvFilter,
};
const TIME_FORMAT: &str =
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]";
fn get_timer() -> OffsetTime<Vec<FormatItem<'static>>> {
OffsetTime::new(
UtcOffset::current_local_offset().unwrap(),
format_description::parse(TIME_FORMAT).unwrap(),
)
}
fn get_day_non_blocking_with_prefix(
path: PathBuf,
prefix: &str,
) -> (NonBlocking, WorkerGuard) {
let appender = tracing_appender::rolling::daily(path, prefix);
tracing_appender::non_blocking(appender)
}
fn init_logs(path: PathBuf) {
let (inbk, _) = get_day_non_blocking_with_prefix(path.clone(), "info.log");
let (enbk, _) = get_day_non_blocking_with_prefix(path, "error.log");
let subscriber = tracing_subscriber::registry()
.with(EnvFilter::from_default_env().add_directive(tracing::Level::TRACE.into()))
.with(Layer::new().with_writer(io::stdout))
.with(
Layer::new()
.pretty()
.with_timer(get_timer())
.with_ansi(false)
.with_writer(enbk.with_max_level(tracing::Level::ERROR)),
)
.with(
Layer::new()
.pretty()
.with_timer(get_timer())
.with_ansi(false)
.with_writer(inbk.with_max_level(tracing::Level::INFO)),
);
tracing::subscriber::set_global_default(subscriber)
.expect("Unable to set a global subscriber");
}
fn main() {
init_logs(std::env::current_dir().unwrap());
test(12);
}
#[instrument(skip(num))]
fn test(num: i32) {
trace!("trace");
info!("{}", num);
error!("hello");
}