gts_logger/
logclient.rs

1use crate::error::GtsLoggerError;
2use crate::logbackend::LogBackend;
3use serde::{Deserialize, Serialize};
4use std::cell::Cell;
5use std::marker::PhantomData;
6
7#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq)]
8pub struct LogEventTs<T> {
9    pub timestamp: u64,
10    pub seqid: u32,
11    pub data: T,
12}
13
14impl<T> LogEventTs<T> {
15    pub fn new(timestamp: u64, seqid: u32, data: T) -> Self {
16        LogEventTs {
17            timestamp,
18            seqid,
19            data,
20        }
21    }
22}
23
24/// LogClient is simple client with timestamp.
25pub struct LogClient<BackendT: LogBackend<LogEventTs<EventT>>, EventT> {
26    backend: BackendT,
27    _data: PhantomData<EventT>,
28    anc: minstant::Anchor,
29    last_ts: Cell<(u64, u32)>,
30}
31
32impl<BackendT: LogBackend<LogEventTs<EventT>>, EventT> LogClient<BackendT, EventT> {
33    pub fn new(backend: BackendT) -> Self {
34        Self {
35            backend: backend,
36            _data: PhantomData {},
37            anc: minstant::Anchor::new(),
38            last_ts: (0, 0).into(),
39        }
40    }
41
42    pub fn log_same(&self, event: EventT) -> Result<(), GtsLoggerError> {
43        let (timestamp, mut seqid) = self.last_ts.get();
44        seqid += 1;
45        self.last_ts.set((timestamp, seqid));
46
47        self.backend.log(LogEventTs {
48            timestamp,
49            seqid,
50            data: event,
51        })
52    }
53
54    pub fn log(&self, event: EventT) -> Result<(), GtsLoggerError> {
55        let ts = minstant::Instant::now();
56        let timestamp = ts.as_unix_nanos(&self.anc);
57        self.last_ts.set((timestamp, 0));
58
59        self.backend.log(LogEventTs {
60            timestamp,
61            seqid: 0,
62            data: event,
63        })
64    }
65
66    pub fn backend(&self) -> &BackendT {
67        &self.backend
68    }
69}