feat: add a time stamp to each log message

Thank-you:  Richard Levitte

Signed-off-by: Lars Wirzenius <liw@liw.fi>
This commit is contained in:
Lars Wirzenius
2024-12-05 13:02:06 +02:00
parent d1151856d5
commit f3d4e4a99b
+15
View File
@@ -4,6 +4,8 @@ use std::{
path::{Path, PathBuf},
};
use time::{macros::format_description, OffsetDateTime};
#[derive(Debug)]
pub struct AdminLog {
filename: PathBuf,
@@ -24,6 +26,9 @@ impl AdminLog {
}
pub fn writeln(&mut self, text: &str) -> Result<(), LogError> {
self.write("[")?;
self.write(&now()?)?;
self.write("] ")?;
self.write(text)?;
self.write("\n")?;
Ok(())
@@ -36,6 +41,13 @@ impl AdminLog {
}
}
fn now() -> Result<String, LogError> {
let fmt = format_description!("[year]-[month]-[day] [hour]:[minute]:[second]Z");
OffsetDateTime::now_utc()
.format(fmt)
.map_err(LogError::TimeFormat)
}
#[derive(Debug, thiserror::Error)]
pub enum LogError {
#[error("failed to open log file {0}")]
@@ -43,4 +55,7 @@ pub enum LogError {
#[error("failed to write to log file {0}")]
WriteLogFile(PathBuf, #[source] std::io::Error),
#[error("failed to format time stamp")]
TimeFormat(#[source] time::error::Format),
}