From f3d4e4a99b582d116c888e23b7915ff4a83ee0f4 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Thu, 5 Dec 2024 13:02:06 +0200 Subject: [PATCH] feat: add a time stamp to each log message Thank-you: Richard Levitte Signed-off-by: Lars Wirzenius --- src/logfile.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/logfile.rs b/src/logfile.rs index be52188..bf8e051 100644 --- a/src/logfile.rs +++ b/src/logfile.rs @@ -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 { + 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), }