rocket_slogger/
transaction.rs

1use chrono::DateTime;
2use rocket::Request;
3use uuid::Uuid;
4
5#[cfg(feature = "local_time")]
6type TimeZone = chrono::Local;
7
8#[cfg(not(feature = "local_time"))]
9type TimeZone = chrono::Utc;
10
11#[derive(Copy, Clone, Debug)]
12pub struct RequestTransaction {
13    pub id: Uuid,
14    pub received: DateTime<TimeZone>,
15}
16
17impl Default for RequestTransaction {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23impl RequestTransaction {
24    pub fn new() -> Self {
25        Self {
26            id: Uuid::new_v4(),
27            received: TimeZone::now(),
28        }
29    }
30
31    pub fn attach_on<'r>(self, request: &'r Request<'_>) -> &'r Self {
32        request.local_cache(|| self)
33    }
34
35    pub fn id_as_string(&self) -> String {
36        self.id
37            .hyphenated()
38            .encode_lower(&mut Uuid::encode_buffer())
39            .to_string()
40    }
41
42    pub fn received_as_string(&self) -> String {
43        self.received.to_rfc3339()
44    }
45
46    pub fn elapsed_as_string(&self) -> String {
47        (TimeZone::now() - self.received).to_string()
48    }
49
50    pub fn elapsed_ns(&self) -> Option<i64> {
51        (TimeZone::now() - self.received).num_nanoseconds()
52    }
53}