move `spawn_logger_thread` to logger module
[ouch.git] / src / utils / logger.rs
blob22ac0397669d7251cf074591411ef44668a62d22
1 use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock};
3 pub use logger_thread::{setup_channel, spawn_logger_thread};
5 use super::colors::{ORANGE, RESET, YELLOW};
6 use crate::accessible::is_running_in_accessible_mode;
8 /// An `[INFO]` log to be displayed if we're not running accessibility mode.
9 ///
10 /// Same as `.info_accessible()`, but only displayed if accessibility mode
11 /// is turned off, which is detected by the function
12 /// `is_running_in_accessible_mode`.
13 ///
14 /// Read more about accessibility mode in `accessible.rs`.
15 #[track_caller]
16 pub fn info(contents: String) {
17     info_with_accessibility(contents, false);
20 /// An `[INFO]` log to be displayed.
21 ///
22 /// Same as `.info()`, but also displays if `is_running_in_accessible_mode`
23 /// returns `true`.
24 ///
25 /// Read more about accessibility mode in `accessible.rs`.
26 #[track_caller]
27 pub fn info_accessible(contents: String) {
28     info_with_accessibility(contents, true);
31 #[track_caller]
32 fn info_with_accessibility(contents: String, accessible: bool) {
33     logger_thread::send_log_message(PrintMessage {
34         contents,
35         accessible,
36         level: MessageLevel::Info,
37     });
40 pub fn warning(contents: String) {
41     logger_thread::send_log_message(PrintMessage {
42         contents,
43         // Warnings are important and unlikely to flood, so they should be displayed
44         accessible: true,
45         level: MessageLevel::Warning,
46     });
49 /// Message object used for sending logs from worker threads to a logging thread via channels.
50 /// See <https://github.com/ouch-org/ouch/issues/643>
51 #[derive(Debug)]
52 pub struct PrintMessage {
53     contents: String,
54     accessible: bool,
55     level: MessageLevel,
58 impl PrintMessage {
59     fn to_processed_message(&self) -> Option<String> {
60         match self.level {
61             MessageLevel::Info => {
62                 if self.accessible {
63                     if is_running_in_accessible_mode() {
64                         Some(format!("{}Info:{} {}", *YELLOW, *RESET, self.contents))
65                     } else {
66                         Some(format!("{}[INFO]{} {}", *YELLOW, *RESET, self.contents))
67                     }
68                 } else if !is_running_in_accessible_mode() {
69                     Some(format!("{}[INFO]{} {}", *YELLOW, *RESET, self.contents))
70                 } else {
71                     None
72                 }
73             }
74             MessageLevel::Warning => {
75                 if is_running_in_accessible_mode() {
76                     Some(format!("{}Warning:{} ", *ORANGE, *RESET))
77                 } else {
78                     Some(format!("{}[WARNING]{} ", *ORANGE, *RESET))
79                 }
80             }
81         }
82     }
85 #[derive(Debug, PartialEq)]
86 enum MessageLevel {
87     Info,
88     Warning,
91 mod logger_thread {
92     use super::*;
94     type LogReceiver = mpsc::Receiver<Option<PrintMessage>>;
95     type LogSender = mpsc::Sender<Option<PrintMessage>>;
97     static SENDER: OnceLock<LogSender> = OnceLock::new();
99     #[track_caller]
100     pub fn setup_channel() -> (LogReceiver, LoggerDropper) {
101         let (tx, rx) = mpsc::channel();
102         SENDER.set(tx).expect("`setup_channel` should only be called once");
103         (rx, LoggerDropper)
104     }
106     #[track_caller]
107     fn get_sender() -> &'static LogSender {
108         SENDER.get().expect("No sender, you need to call `setup_channel` first")
109     }
111     pub fn spawn_logger_thread(log_receiver: LogReceiver, synchronization_pair: Arc<(Mutex<bool>, Condvar)>) {
112         rayon::spawn(move || {
113             const BUFFER_CAPACITY: usize = 10;
114             let mut buffer = Vec::<String>::with_capacity(BUFFER_CAPACITY);
116             loop {
117                 let msg = log_receiver.recv().expect("Failed to receive log message");
119                 let is_shutdown_message = msg.is_none();
121                 // Append message to buffer
122                 if let Some(msg) = msg.as_ref().and_then(PrintMessage::to_processed_message) {
123                     buffer.push(msg);
124                 }
126                 let should_flush = buffer.len() == BUFFER_CAPACITY || is_shutdown_message;
128                 if should_flush {
129                     let text = buffer.join("\n");
130                     eprintln!("{text}");
131                     buffer.clear();
132                 }
134                 if is_shutdown_message {
135                     break;
136                 }
137             }
139             // Wake up the main thread
140             let (lock, cvar) = &*synchronization_pair;
141             let mut flushed = lock.lock().unwrap();
142             *flushed = true;
143             cvar.notify_one();
144         });
145     }
147     #[track_caller]
148     pub fn send_log_message(msg: PrintMessage) {
149         send_message(Some(msg));
150     }
152     #[track_caller]
153     fn send_message(msg: Option<PrintMessage>) {
154         get_sender().send(msg).expect("Failed to send internal message");
155     }
157     pub struct LoggerDropper;
159     impl Drop for LoggerDropper {
160         fn drop(&mut self) {
161             send_message(None);
162         }
163     }