tracing_configuration/
time.rs

1use std::time::Instant;
2
3use tracing_subscriber::fmt::{
4    format::Writer,
5    time::{ChronoLocal, ChronoUtc, SystemTime, Uptime},
6};
7
8/// Implementor of [`tracing_subscriber::fmt::time::FormatTime`], constructed [`From`] [`Timer`](crate::Timer).
9pub struct FormatTime(FormatTimeInner);
10
11impl From<crate::Timer> for FormatTime {
12    fn from(value: crate::Timer) -> Self {
13        Self(value.into())
14    }
15}
16
17impl tracing_subscriber::fmt::time::FormatTime for FormatTime {
18    fn format_time(&self, w: &mut Writer<'_>) -> std::fmt::Result {
19        self.0.format_time(w)
20    }
21}
22
23enum FormatTimeInner {
24    None(()),
25    Local(ChronoLocal),
26    Utc(ChronoUtc),
27    System(SystemTime),
28    Uptime(Uptime),
29}
30
31impl From<crate::Timer> for FormatTimeInner {
32    fn from(value: crate::Timer) -> Self {
33        match value {
34            crate::Timer::None => Self::None(()),
35            crate::Timer::Local(it) => Self::Local(match it {
36                Some(it) if it == "%+" => ChronoLocal::rfc_3339(),
37                None => ChronoLocal::rfc_3339(),
38                Some(it) => ChronoLocal::new(it),
39            }),
40            crate::Timer::Utc(it) => Self::Utc(match it {
41                Some(it) if it == "%+" => ChronoUtc::rfc_3339(),
42                None => ChronoUtc::rfc_3339(),
43                Some(it) => ChronoUtc::new(it),
44            }),
45            crate::Timer::System => Self::System(SystemTime),
46            crate::Timer::Uptime => Self::Uptime(Uptime::from(Instant::now())),
47        }
48    }
49}
50
51impl tracing_subscriber::fmt::time::FormatTime for FormatTimeInner {
52    fn format_time(&self, w: &mut Writer<'_>) -> std::fmt::Result {
53        match self {
54            Self::None(it) => it.format_time(w),
55            Self::Local(it) => it.format_time(w),
56            Self::Utc(it) => it.format_time(w),
57            Self::System(it) => it.format_time(w),
58            Self::Uptime(it) => it.format_time(w),
59        }
60    }
61}