1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
use chrono::{DateTime, Local}; /// Deferred timestamp creation. /// /// Is used to ensure that a log record that is sent to multiple outputs /// (in maybe different formats) always uses the same timestamp. #[derive(Debug)] pub struct DeferredNow(Option<DateTime<Local>>); impl Default for DeferredNow { fn default() -> Self { Self::new() } } impl<'a> DeferredNow { /// Constructs a new instance, but does not generate the timestamp. #[must_use] pub fn new() -> Self { Self(None) } /// Retrieve the timestamp. /// /// Requires mutability because the first caller will generate the timestamp. pub fn now(&'a mut self) -> &'a DateTime<Local> { if self.0.is_none() { self.0 = Some(Local::now()); } self.0.as_ref().unwrap() } }