My personal-knowledge-system, with deeply integrated task tracking and long term goal planning capabilities.
1use std::{
2 fs::{File, create_dir_all},
3 sync::LazyLock,
4};
5
6use color_eyre::eyre::Result;
7use tracing::Level;
8use tracing_error::ErrorLayer;
9use tracing_subscriber::{EnvFilter, Layer, fmt, layer::SubscriberExt, util::SubscriberInitExt};
10
11use crate::config;
12
13/// The user-set log level if it exists.
14pub static LOG_LEVEL_ENV: LazyLock<String> =
15 LazyLock::new(|| format!("{}_LOG_LEVEL", config::PROJECT_NAME.clone()));
16
17/// The logfile name set by our package name.
18pub static LOG_FILE: LazyLock<String> = LazyLock::new(|| format!("{}.log", env!("CARGO_PKG_NAME")));
19
20/// Initializes the logger, which writes logs to a `log_file` in the data dir.
21///
22/// NOTE: log level is configurable via the `RUST_LOG` env var or the
23/// `FILAMENTS_LOG_LEVEL` env var
24pub fn init() -> Result<()> {
25 let directory = config::get_data_dir();
26
27 create_dir_all(&directory)?;
28
29 let log_path = directory.join(LOG_FILE.clone());
30 let log_file = File::create(log_path)?;
31
32 let env_filter = EnvFilter::builder().with_default_directive(Level::INFO.into());
33
34 // If `RUST_LOG` is set, use that as default,, or use value of `LOG_ENV` variable.
35 let env_filter = env_filter
36 .try_from_env()
37 .or_else(|_| env_filter.with_env_var(LOG_LEVEL_ENV.clone()).from_env())?;
38
39 let file_subscriber = fmt::layer()
40 .with_file(true)
41 .with_line_number(true)
42 .with_writer(log_file)
43 .with_target(false)
44 .with_ansi(false)
45 .with_filter(env_filter);
46 tracing_subscriber::registry()
47 .with(file_subscriber)
48 .with(ErrorLayer::default())
49 .try_init()?;
50
51 Ok(())
52}