vault_tasks_core/
logging.rs1use color_eyre::Result;
2use tracing::debug;
3use tracing_error::ErrorLayer;
4use tracing_subscriber::{EnvFilter, fmt, prelude::*};
5
6use crate::config;
7
8lazy_static::lazy_static! {
9 pub static ref LOG_ENV: String = format!("{}_LOGLEVEL", config::PROJECT_NAME.clone());
10 pub static ref LOG_FILE: String = format!("{}.log", env!("CARGO_PKG_NAME"));
11}
12
13pub fn init() -> Result<()> {
14 let directory = config::get_data_dir();
15 std::fs::create_dir_all(directory.clone())?;
16 let log_path = directory.join(LOG_FILE.clone());
17 let log_file = std::fs::File::create(log_path.clone())?;
18
19 let env_filter = EnvFilter::builder().with_default_directive(tracing::Level::INFO.into());
21
22 let env_filter = env_filter
24 .try_from_env()
25 .or_else(|_| env_filter.with_env_var(LOG_ENV.clone()).from_env())
26 .unwrap_or_else(|_| {
27 EnvFilter::builder()
29 .with_default_directive(tracing::Level::INFO.into())
30 .from_env_lossy()
31 });
32
33 let file_subscriber = fmt::layer()
34 .with_file(true)
35 .with_line_number(true)
36 .with_writer(log_file)
37 .with_target(false)
38 .with_ansi(false)
39 .with_filter(env_filter);
40
41 tracing_subscriber::registry()
42 .with(file_subscriber)
43 .with(ErrorLayer::default())
44 .try_init()?;
45
46 debug!("Logging initialized successfully. Log file: {:?}", log_path);
48 Ok(())
49}