hp_log/
event.rs

1use time;
2use crate::filter::FilterLevel;
3use std::fmt;
4
5use log::Record;
6
7pub struct LogicEvent {
8    pub level: FilterLevel,
9    pub content: String,
10}
11
12pub struct Event {
13    pub time_spec: time::Timespec,
14    pub tm: time::Tm,
15    pub level: FilterLevel,
16    pub thread_tag: String,
17    pub file: String,
18    pub line: u32,
19    pub msg: String,
20}
21
22impl Event {
23    pub fn new(level: FilterLevel, thread_tag: String, file: &'static str, line: u32, msg: fmt::Arguments) -> Self {
24        Self {
25            time_spec: time::get_time(),
26            tm: time::now(),
27            level,
28            thread_tag,
29            file: file.to_string(),
30            line,
31            msg: msg.to_string(),
32        }
33    }
34
35    pub fn from_record(thread_tag: String, record: &Record) -> Self {
36        Self {
37            time_spec: time::get_time(),
38            tm: time::now(),
39            level: record.level().into(),
40            thread_tag,
41            file: record.file().unwrap_or("").to_string(),
42            line: record.line().unwrap_or(0),
43            msg: format!("{}", record.args()),
44        }
45    }
46
47    pub fn format_by_default(&self) -> String {
48        let t = self.tm.strftime("[%Y-%m-%d %H:%M:%S]").unwrap();
49        format!("{}-{}-[{}]-{}:{}  {}\n", t, self.thread_tag, self.level.to_str(), self.file, self.line, self.msg)
50    }
51
52    pub fn to_logic(&self) -> LogicEvent {
53        LogicEvent {
54            content: self.format_by_default(),
55            level: self.level,
56        }
57    }
58}
59
60impl fmt::Display for Event {
61    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62        write!(f,
63               "(tm:{:?} level:{} thread_tag:{} file:{} line:{} msg:{})",
64               self.tm,
65               self.level.to_str(),
66               self.thread_tag,
67               self.file,
68               self.line,
69               self.msg
70        )
71    }
72}
73