xref: /DragonOS/tools/debugging/logmonitor/src/logging.rs (revision 338f6903262c5031abad3c8e361813355a27fcdb)
1 use std::sync::mpsc;
2 
3 use log::LevelFilter;
4 use simple_logger::LogBackend;
5 
6 use crate::command::CommandLineArgs;
7 
8 /// Initialize the logging system.
9 pub fn init(cmd_args: &CommandLineArgs) -> LoggingInitResult {
10     let mut builder = simple_logger::SimpleLogger::new().with_level(LevelFilter::Info);
11 
12     let mut result = LoggingInitResult::new(None);
13 
14     if cmd_args.tui {
15         let channel: (mpsc::Sender<String>, mpsc::Receiver<String>) = mpsc::channel::<String>();
16         builder = builder.with_backend(Box::new(TUILoggingBackend::new(channel.0)));
17         result.tui_receiver = Some(channel.1);
18     }
19 
20     builder.init().expect("failed to initialize logging");
21 
22     return result;
23 }
24 
25 #[derive(Debug)]
26 pub struct LoggingInitResult {
27     /// Logging backend receiver.
28     pub tui_receiver: Option<mpsc::Receiver<String>>,
29 }
30 
31 impl LoggingInitResult {
32     pub fn new(tui_receiver: Option<mpsc::Receiver<String>>) -> Self {
33         Self { tui_receiver }
34     }
35 }
36 
37 pub struct TUILoggingBackend {
38     sender: mpsc::Sender<String>,
39 }
40 
41 impl TUILoggingBackend {
42     pub fn new(sender: mpsc::Sender<String>) -> Self {
43         Self { sender }
44     }
45 }
46 
47 impl LogBackend for TUILoggingBackend {
48     fn log(&self, message: String) {
49         self.sender.send(message).ok();
50     }
51 }
52