]>
Commit | Line | Data |
---|---|---|
e74abb32 XL |
1 | use std::fmt; |
2 | use std::time::SystemTime; | |
3 | ||
4 | use humantime::{format_rfc3339_nanos, format_rfc3339_seconds}; | |
5 | ||
6 | use ::fmt::Formatter; | |
7 | ||
8 | pub(in ::fmt) mod glob { | |
9 | pub use super::*; | |
10 | } | |
11 | ||
12 | impl Formatter { | |
13 | /// Get a [`Timestamp`] for the current date and time in UTC. | |
14 | /// | |
15 | /// # Examples | |
16 | /// | |
17 | /// Include the current timestamp with the log record: | |
18 | /// | |
19 | /// ``` | |
20 | /// use std::io::Write; | |
21 | /// | |
22 | /// let mut builder = env_logger::Builder::new(); | |
23 | /// | |
24 | /// builder.format(|buf, record| { | |
25 | /// let ts = buf.timestamp(); | |
26 | /// | |
27 | /// writeln!(buf, "{}: {}: {}", ts, record.level(), record.args()) | |
28 | /// }); | |
29 | /// ``` | |
30 | /// | |
31 | /// [`Timestamp`]: struct.Timestamp.html | |
32 | pub fn timestamp(&self) -> Timestamp { | |
33 | Timestamp(SystemTime::now()) | |
34 | } | |
35 | ||
36 | /// Get a [`PreciseTimestamp`] for the current date and time in UTC with nanos. | |
37 | pub fn precise_timestamp(&self) -> PreciseTimestamp { | |
38 | PreciseTimestamp(SystemTime::now()) | |
39 | } | |
40 | } | |
41 | ||
42 | /// An [RFC3339] formatted timestamp. | |
43 | /// | |
44 | /// The timestamp implements [`Display`] and can be written to a [`Formatter`]. | |
45 | /// | |
46 | /// [RFC3339]: https://www.ietf.org/rfc/rfc3339.txt | |
47 | /// [`Display`]: https://doc.rust-lang.org/stable/std/fmt/trait.Display.html | |
48 | /// [`Formatter`]: struct.Formatter.html | |
49 | pub struct Timestamp(SystemTime); | |
50 | ||
51 | /// An [RFC3339] formatted timestamp with nanos. | |
52 | /// | |
53 | /// [RFC3339]: https://www.ietf.org/rfc/rfc3339.txt | |
54 | #[derive(Debug)] | |
55 | pub struct PreciseTimestamp(SystemTime); | |
56 | ||
57 | impl fmt::Debug for Timestamp { | |
58 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
59 | /// A `Debug` wrapper for `Timestamp` that uses the `Display` implementation. | |
60 | struct TimestampValue<'a>(&'a Timestamp); | |
61 | ||
62 | impl<'a> fmt::Debug for TimestampValue<'a> { | |
63 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
64 | fmt::Display::fmt(&self.0, f) | |
65 | } | |
66 | } | |
67 | ||
68 | f.debug_tuple("Timestamp") | |
69 | .field(&TimestampValue(&self)) | |
70 | .finish() | |
71 | } | |
72 | } | |
73 | ||
74 | impl fmt::Display for Timestamp { | |
75 | fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { | |
76 | format_rfc3339_seconds(self.0).fmt(f) | |
77 | } | |
78 | } | |
79 | ||
80 | impl fmt::Display for PreciseTimestamp { | |
81 | fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { | |
82 | format_rfc3339_nanos(self.0).fmt(f) | |
83 | } | |
84 | } |