fix(log): panic when trying to open alogfile in a dir that did not exist
cargo devel CI / cargo CI (push) Has been cancelled Details

This commit is contained in:
Christoph J. Scherr 2024-09-08 01:14:04 +02:00
parent 51e2c3029e
commit a9fbcf9518
2 changed files with 21 additions and 15 deletions

View File

@ -20,4 +20,6 @@ pub enum Error {
/// any other error type, wrapped in [`anyhow::Error`] /// any other error type, wrapped in [`anyhow::Error`]
#[error(transparent)] #[error(transparent)]
Other(#[from] anyhow::Error), Other(#[from] anyhow::Error),
#[error("Tried to open the logfile, but logging to file was not requested")]
LogfileButNoFilelog,
} }

View File

@ -151,9 +151,14 @@ impl LoggerBuilder {
)); ));
if self.log_to_file { if self.log_to_file {
tracing_subscriber::registry() tracing_subscriber::registry()
.with(layer.and_then( .with(
tracing_subscriber::fmt::layer().with_writer(self.logfile().unwrap()), layer.and_then(
)) tracing_subscriber::fmt::layer().with_writer(
self.logfile()?
.expect("logging to file is requested but logfile returned None"),
),
),
)
.init(); .init();
} else { } else {
tracing_subscriber::registry().with(layer).init(); tracing_subscriber::registry().with(layer).init();
@ -163,25 +168,24 @@ impl LoggerBuilder {
Ok(Logger {}) Ok(Logger {})
} }
fn logfile(&self) -> Option<std::fs::File> { /// Opens a new file for logging to.
///
/// Format: `{log_dir}/{consumer_name}_2024-09-01.log`
///
/// Will be none if [`Self::log_to_file`] is [false].
fn logfile(&self) -> Result<Option<std::fs::File>> {
if !self.log_to_file { if !self.log_to_file {
return None; return Err(Error::LogfileButNoFilelog.into());
} }
let mut path = self.log_dir.clone(); let mut path = self.log_dir.clone();
std::fs::create_dir_all(&path)?;
path.push(format!( path.push(format!(
"{}.{}.log", "{}_{}.log",
libpt_core::get_crate_name().unwrap_or_else(|| "logfile".to_string()), libpt_core::get_crate_name().unwrap_or_else(|| "logfile".to_string()),
chrono::Local::now().date_naive() chrono::Local::now().date_naive()
)); ));
let file = match std::fs::File::create(path) { let file = std::fs::File::create(path)?;
Ok(f) => f, Ok(Some(file))
Err(e) => {
eprintln!("libpt: could not start logging to file: {e}");
return None;
}
};
Some(file)
} }
/// enable or disable logging to and creating of logfiles /// enable or disable logging to and creating of logfiles