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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
use chrono::{
format::{DelayedFormat, StrftimeItems},
DateTime, Local, SecondsFormat, Utc,
};
#[cfg(feature = "syslog_writer")]
use chrono::{Datelike, Timelike};
use std::sync::{Arc, Mutex};
#[derive(Debug, Default)]
pub struct DeferredNow(Option<DateTime<Local>>);
impl<'a> DeferredNow {
#[must_use]
pub fn new() -> Self {
Self(None)
}
#[allow(dead_code)]
#[must_use]
pub(crate) fn new_from_datetime(dt: DateTime<Local>) -> Self {
Self(Some(dt))
}
pub fn now(&'a mut self) -> &'a DateTime<Local> {
self.0.get_or_insert_with(Local::now)
}
pub fn now_utc_owned(&'a mut self) -> DateTime<Utc> {
(*self.now()).into()
}
pub fn format<'b>(&'a mut self, fmt: &'b str) -> DelayedFormat<StrftimeItems<'b>> {
if use_utc() {
self.now_utc_owned().format(fmt)
} else {
self.now().format(fmt)
}
}
pub fn format_rfc3339(&mut self) -> String {
if use_utc() {
self.now_utc_owned()
.to_rfc3339_opts(SecondsFormat::Millis, false)
} else {
self.now().to_rfc3339_opts(SecondsFormat::Millis, false)
}
}
#[cfg(feature = "syslog_writer")]
pub(crate) fn format_rfc3164(&mut self) -> String {
let (date, time) = if use_utc() {
let now = self.now_utc_owned();
(now.date_naive(), now.time())
} else {
let now = self.now();
(now.date_naive(), now.time())
};
format!(
"{mmm} {dd:>2} {hh:02}:{mm:02}:{ss:02}",
mmm = match date.month() {
1 => "Jan",
2 => "Feb",
3 => "Mar",
4 => "Apr",
5 => "May",
6 => "Jun",
7 => "Jul",
8 => "Aug",
9 => "Sep",
10 => "Oct",
11 => "Nov",
12 => "Dec",
_ => unreachable!(),
},
dd = date.day(),
hh = time.hour(),
mm = time.minute(),
ss = time.second()
)
}
pub fn force_utc() {
let mut guard = FORCE_UTC.lock().unwrap();
match *guard {
Some(false) => {
panic!("offset is already initialized not to enforce UTC");
}
Some(true) => {
}
None => *guard = Some(true),
}
}
#[allow(dead_code)]
pub(crate) fn set_force_utc(b: bool) {
let mut guard = FORCE_UTC.lock().unwrap();
*guard = Some(b);
}
}
lazy_static::lazy_static! {
static ref FORCE_UTC: Arc<Mutex<Option<bool>>> =
Arc::new(Mutex::new(None));
}
fn use_utc() -> bool {
let mut force_utc_guard = FORCE_UTC.lock().unwrap();
if let Some(true) = *force_utc_guard {
true
} else {
if force_utc_guard.is_none() {
*force_utc_guard = Some(false);
}
false
}
}
#[cfg(test)]
mod test {
use crate::DeferredNow;
use chrono::{
DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, SecondsFormat, TimeZone, Utc,
};
#[test]
fn test_timestamp_taken_only_once() {
let mut deferred_now = super::DeferredNow::new();
let once = *deferred_now.now();
std::thread::sleep(std::time::Duration::from_millis(30));
let again = *deferred_now.now();
assert_eq!(once, again);
println!("Now: {}", deferred_now.format("%Y-%m-%d %H:%M:%S%.6f %:z"));
println!("Now: {}", once.format("%Y-%m-%d %H:%M:%S%.6f %:z"));
println!("Now: {}", again.format("%Y-%m-%d %H:%M:%S%.6f %:z"));
}
fn utc_and_offset_timestamps() -> (DateTime<Utc>, DateTime<FixedOffset>) {
let naive_datetime = NaiveDateTime::new(
NaiveDate::from_ymd_opt(2021, 4, 29).unwrap(),
NaiveTime::from_hms_milli_opt(13, 14, 15, 678).unwrap(),
);
(
Utc.from_local_datetime(&naive_datetime).unwrap(),
FixedOffset::east_opt(3600)
.unwrap()
.from_local_datetime(&naive_datetime)
.unwrap(),
)
}
fn get_deferred_nows() -> (DeferredNow, DeferredNow) {
let (ts_utc, ts_plus1) = utc_and_offset_timestamps();
(
DeferredNow::new_from_datetime(ts_utc.into()),
DeferredNow::new_from_datetime(ts_plus1.into()),
)
}
#[test]
fn test_chrono_rfc3339() {
let (ts_utc, ts_plus1) = utc_and_offset_timestamps();
assert_eq!(
ts_utc.to_rfc3339_opts(SecondsFormat::Millis, true),
"2021-04-29T13:14:15.678Z",
);
assert_eq!(
ts_plus1.to_rfc3339_opts(SecondsFormat::Millis, true),
"2021-04-29T13:14:15.678+01:00",
);
assert_eq!(
ts_utc.to_rfc3339_opts(SecondsFormat::Millis, false),
"2021-04-29T13:14:15.678+00:00",
);
assert_eq!(
ts_plus1.to_rfc3339_opts(SecondsFormat::Millis, false),
"2021-04-29T13:14:15.678+01:00",
);
}
#[test]
fn test_formats() {
#[cfg(feature = "syslog_writer")]
{
log::info!("test rfc3164");
super::DeferredNow::set_force_utc(true);
let (mut dn1, mut dn2) = get_deferred_nows();
assert_eq!("Apr 29 13:14:15", &dn1.format_rfc3164());
assert_eq!("Apr 29 12:14:15", &dn2.format_rfc3164());
}
log::info!("test rfc3339");
{
super::DeferredNow::set_force_utc(false);
let (mut dn1, mut dn2) = get_deferred_nows();
log::info!("2021-04-29T15:14:15.678+02:00, {}", &dn1.format_rfc3339());
log::info!("2021-04-29T14:14:15.678+02:00, {}", &dn2.format_rfc3339());
super::DeferredNow::set_force_utc(true);
let (mut dn1, mut dn2) = get_deferred_nows();
assert_eq!("2021-04-29T13:14:15.678+00:00", &dn1.format_rfc3339());
assert_eq!("2021-04-29T12:14:15.678+00:00", &dn2.format_rfc3339());
}
}
}