1use std::{borrow::Cow, env, fs::File, path::PathBuf};
2
3use color_eyre::{Result, eyre::Context};
4use tracing_error::ErrorLayer;
5use tracing_subscriber::{EnvFilter, fmt, prelude::*};
6
7use crate::config::Config;
8
9pub fn init(config: &Config) -> Result<Option<PathBuf>> {
11 let env_filter = env::var("INTELLI_LOG").ok();
12 if config.logs.enabled || env_filter.is_some() {
13 let log_path = config.data_dir.join("intelli-shell.log");
15 let log_file = File::create(&log_path)
16 .wrap_err_with(|| format!("Couldn't create the log file: {}", log_path.display()))?;
17 let filter = env_filter
19 .map(Cow::from)
20 .unwrap_or_else(|| Cow::from(&config.logs.filter));
21 let env_filter = EnvFilter::builder()
22 .with_default_directive(tracing::Level::WARN.into())
23 .parse(filter)
24 .wrap_err("Couldn't parse the log filter")?;
25 let file_subscriber = fmt::layer()
27 .with_file(true)
28 .with_line_number(true)
29 .with_writer(log_file)
30 .with_target(false)
31 .with_ansi(false)
32 .with_filter(env_filter);
33 tracing_subscriber::registry()
34 .with(file_subscriber)
35 .with(ErrorLayer::default())
36 .init();
37 Ok(Some(log_path))
38 } else {
39 Ok(None)
40 }
41}