xref: /DragonOS/kernel/src/filesystem/procfs/log.rs (revision 013ffb708fab7760ea999c1edf462c69ac68f0ac)
1 use core::fmt::{Display, Formatter, Result};
2 
3 use alloc::string::String;
4 
5 use crate::time::PosixTimeSpec;
6 
7 // /// 日志类型
8 // #[derive(Default, Clone, Debug)]
9 // pub enum LogType {
10 //     /// 启动信息
11 //     Startup,
12 //     /// 驱动信息
13 //     Driver,
14 //     /// 系统信息
15 //     System,
16 //     /// 硬件信息
17 //     Hardware,
18 //     /// 内核模块信息
19 //     KernelModule,
20 //     /// 内核调试信息
21 //     KernelDebug,
22 //     #[default]
23 //     Default,
24 // }
25 
26 /// 日志级别
27 #[derive(Default, Clone, PartialEq, Debug)]
28 pub enum LogLevel {
29     EMERG = 0,
30     ALERT = 1,
31     CRIT = 2,
32     ERR = 3,
33     WARN = 4,
34     NOTICE = 5,
35     INFO = 6,
36     DEBUG = 7,
37     #[default]
38     DEFAULT = 8,
39 }
40 
41 impl From<usize> for LogLevel {
42     fn from(value: usize) -> Self {
43         match value {
44             0 => LogLevel::EMERG,
45             1 => LogLevel::ALERT,
46             2 => LogLevel::CRIT,
47             3 => LogLevel::ERR,
48             4 => LogLevel::WARN,
49             5 => LogLevel::NOTICE,
50             6 => LogLevel::INFO,
51             7 => LogLevel::DEBUG,
52             _ => LogLevel::DEFAULT,
53         }
54     }
55 }
56 
57 /// 日志消息
58 #[derive(Default, Clone, Debug)]
59 pub struct LogMessage {
60     /// 时间戳
61     timestamp: PosixTimeSpec,
62     /// 日志级别
63     level: LogLevel,
64     // /// 日志类型
65     // log_type: LogType,
66     /// 日志消息
67     message: String,
68 }
69 
70 impl LogMessage {
71     pub fn new(timestamp: PosixTimeSpec, level: LogLevel, message: String) -> Self {
72         LogMessage {
73             timestamp,
74             level,
75             message,
76         }
77     }
78 
79     pub fn level(&self) -> LogLevel {
80         self.level.clone()
81     }
82 }
83 
84 impl Display for LogMessage {
85     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
86         let timestamp = &self.timestamp;
87         let level = match self.level {
88             LogLevel::EMERG => "EMERG",
89             LogLevel::ALERT => "ALERT",
90             LogLevel::CRIT => "CRIT",
91             LogLevel::ERR => "ERR",
92             LogLevel::WARN => "WARNING",
93             LogLevel::NOTICE => "NOTICE",
94             LogLevel::INFO => "INFO",
95             LogLevel::DEBUG => "DEBUG",
96             LogLevel::DEFAULT => "Default",
97         };
98 
99         let message = &self.message;
100 
101         let res = format!(
102             "<{}>[{}.{}] : {}\n",
103             level, timestamp.tv_sec, timestamp.tv_nsec, message
104         );
105         return write!(f, "{}", res);
106     }
107 }
108