1use std::str::FromStr;
2use std::{path::Path, sync::Arc};
3
4use crate::config::AgentServerConfig;
5use tracing::level_filters::LevelFilter;
6use tracing_appender::non_blocking::WorkerGuard;
7use tracing_subscriber::fmt::time::ChronoUtc;
8
9use crate::error::AgentServerError;
10
11const TRACE_FILE_DIR_PATH: &str = "log";
12
13const LOG_FILE_NAME_PREFIX: &str = "ppaass-agent";
14
15pub fn init_log(config: Arc<AgentServerConfig>) -> Result<WorkerGuard, AgentServerError> {
16 let (trace_file_appender, trace_appender_guard) = tracing_appender::non_blocking(
17 tracing_appender::rolling::daily(Path::new(TRACE_FILE_DIR_PATH), LOG_FILE_NAME_PREFIX),
18 );
19 let subscriber = tracing_subscriber::fmt()
20 .with_max_level(LevelFilter::from_str(config.max_log_level()).unwrap_or(LevelFilter::ERROR))
21 .with_writer(trace_file_appender)
22 .with_line_number(true)
23 .with_level(true)
24 .with_thread_ids(true)
25 .with_thread_names(true)
26 .with_timer(ChronoUtc::rfc_3339())
27 .with_ansi(false)
28 .finish();
29 tracing::subscriber::set_global_default(subscriber).expect("Fail to initialize log system.");
30 Ok(trace_appender_guard)
31}