use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tracing_subscriber::filter::EnvFilter;
#[derive(Debug, thiserror::Error)]
pub enum LoggingError {
#[error("cannot open log file {path}: {source}")]
OpenFile {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("a tracing subscriber was already installed")]
AlreadyInitialised,
}
pub fn init_file_logging(path: &Path, directive: &str) -> Result<(), LoggingError> {
let file = open_log_file(path)?;
let filter = EnvFilter::try_from_env("RATASM_LOG")
.or_else(|_| EnvFilter::try_new(directive))
.unwrap_or_else(|_| EnvFilter::new("info"));
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(Mutex::new(file))
.with_ansi(false)
.with_target(true)
.try_init()
.map_err(|_| LoggingError::AlreadyInitialised)
}
fn open_log_file(path: &Path) -> Result<File, LoggingError> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent).map_err(|source| LoggingError::OpenFile {
path: path.to_path_buf(),
source,
})?;
}
}
OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|source| LoggingError::OpenFile {
path: path.to_path_buf(),
source,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn creates_missing_parent_directories() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested/deeper/ratasm.log");
assert!(open_log_file(&path).is_ok());
assert!(path.exists());
}
#[test]
fn reports_unwritable_paths_without_panicking() {
let dir = tempfile::tempdir().unwrap();
let err = open_log_file(dir.path()).unwrap_err();
assert!(matches!(err, LoggingError::OpenFile { .. }));
}
}