cyfs_debug/log/
target.rs

1use super::constants::*;
2use cyfs_base::*;
3
4use log::Record;
5use serde::{Serialize, Deserialize};
6
7#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct CyfsLogRecord {
9    level: LogLevel,
10    target: String,
11    time: u64,
12    file: Option<String>,
13    line: Option<u32>,
14    content: String,
15}
16
17impl CyfsLogRecord {
18    pub fn new(record: &Record) -> Self {
19        let level: LogLevel = record.metadata().level().into();
20        let target = record.metadata().target().to_owned();
21        let time = cyfs_base::bucky_time_now();
22
23        let content = format!("{}", record.args());
24
25        Self {
26            level,
27            target,
28            time,
29            file: record.file().map(|v| v.to_owned()),
30            line: record.line(),
31            content,
32        }
33    }
34
35    pub fn easy_log(level: LogLevel, content: String) -> Self {
36        Self {
37            level,
38            time: cyfs_base::bucky_time_now(),
39            target: "".to_string(),
40            file: None,
41            line: None,
42            content,
43        }
44    }
45
46    pub fn content(&self) -> String {
47        self.content.clone()
48    }
49
50    pub fn level(&self) -> LogLevel {
51        self.level
52    }
53
54    pub fn time(&self) -> u64 {
55        self.time
56    }
57
58    pub fn file(&self) -> String {
59        match &self.file {
60            Some(f) => f.clone(),
61            _ => "".to_string(),
62        }
63    }
64
65    pub fn line(&self) -> u32 {
66        match &self.line {
67            Some(l) => *l,
68            _ => 0,
69        }
70    }
71}
72
73use chrono::offset::Local;
74use chrono::DateTime;
75
76
77impl std::fmt::Display for CyfsLogRecord {
78    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
79        let system_time = bucky_time_to_system_time(self.time);
80        let datetime: DateTime<Local> = system_time.into();
81        let time_str = datetime.format("%Y-%m-%d %H:%M:%S%.3f %:z");
82
83        write!(
84            f,
85            "[{}] {} [{}:{}] {}",
86            time_str,
87            self.level.to_string().to_uppercase(),
88            self.file.as_deref().unwrap_or("<unnamed>"),
89            self.line.unwrap_or(0),
90            self.content,
91        )
92    }
93}
94
95pub trait CyfsLogTarget: Send + Sync {
96    fn log(&self, record: &CyfsLogRecord);
97}
98
99pub struct ConsoleCyfsLogTarget {}
100
101impl CyfsLogTarget for ConsoleCyfsLogTarget {
102    fn log(&self, record: &CyfsLogRecord) {
103        println!(">>>{}", record);
104    }
105}