#![warn(dead_code)]
use std::path::PathBuf;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use super::scm;
use crate::common::paths;
pub const DEFAULT_FILTER: &str = "all_smi=info,tower_http=warn";
pub fn log_dir() -> PathBuf {
paths::program_data_app_dir(&paths::program_data_root()).join(scm::LOG_DIR_NAME)
}
pub fn init() -> Result<PathBuf, String> {
let dir = log_dir();
std::fs::create_dir_all(&dir)
.map_err(|e| format!("could not create the log directory {}: {e}", dir.display()))?;
let appender = RollingFileAppender::builder()
.rotation(Rotation::DAILY)
.filename_prefix(scm::LOG_FILE_PREFIX)
.filename_suffix(scm::LOG_FILE_SUFFIX)
.max_log_files(scm::LOG_RETENTION_FILES)
.build(&dir)
.map_err(|e| format!("could not open a log file in {}: {e}", dir.display()))?;
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(DEFAULT_FILTER));
tracing_subscriber::registry()
.with(filter)
.with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(appender),
)
.try_init()
.map_err(|e| format!("could not install the file logging subscriber: {e}"))?;
Ok(dir)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_log_directory_sits_under_the_program_data_app_dir() {
let dir = log_dir();
assert!(dir.ends_with(scm::LOG_DIR_NAME), "got {}", dir.display());
assert!(
dir.starts_with(paths::program_data_root()),
"logs must live under %PROGRAMDATA%: {}",
dir.display()
);
}
#[test]
fn the_default_filter_is_quieter_than_the_foreground_default() {
assert!(DEFAULT_FILTER.contains("all_smi=info"));
assert!(!DEFAULT_FILTER.contains("debug"));
}
}