1use std::{panic, sync::mpsc::Sender, thread};
26
27use colored::Colorize;
28use log::{Level, LevelFilter};
29use time::{OffsetDateTime, macros::format_description};
30
31#[derive(Clone)]
32struct Logger(Vec<String>, Sender<(OutputChannel, String)>);
33
34enum OutputChannel {
35 Standard,
36 Error,
37}
38
39impl From<Level> for OutputChannel {
40 fn from(level: Level) -> Self {
41 match level {
42 Level::Error => OutputChannel::Error,
43 _ => OutputChannel::Standard,
44 }
45 }
46}
47
48impl Logger {
49 fn new(modules: Vec<String>) -> Self {
50 let (sender, receiver) = std::sync::mpsc::channel();
51
52 thread::spawn(move || {
53 for (output, line) in receiver {
54 match output {
55 OutputChannel::Standard => {
56 println!("{line}");
57 }
58 OutputChannel::Error => {
59 eprintln!("{line}");
60 }
61 }
62 }
63 });
64
65 Self(modules, sender)
66 }
67}
68
69impl log::Log for Logger {
70 fn enabled(&self, metadata: &log::Metadata) -> bool {
71 if self.0.is_empty() {
72 return true;
73 }
74
75 for module in &self.0 {
76 if metadata.target() == *module || metadata.target().starts_with(&format!("{module}::"))
77 {
78 return true;
79 }
80 }
81
82 false
83 }
84
85 fn log(&self, record: &log::Record) {
86 if self.enabled(record.metadata()) {
87 self.1
88 .send((
89 record.level().into(),
90 format!(
91 "{} {} {}",
92 get_formatted_timestamp(),
93 get_formatted_level(record.level().as_str()),
94 record.args(),
95 ),
96 ))
97 .ok();
98 }
99 }
100
101 fn flush(&self) {}
102}
103
104use std::sync::OnceLock;
105
106static LOGGER: OnceLock<Logger> = OnceLock::new();
107
108pub fn init(filter: LevelFilter, modules: impl IntoIterator<Item = impl ToString>) {
130 LOGGER
131 .set(Logger::new(
132 modules.into_iter().map(|m| m.to_string()).collect(),
133 ))
134 .ok();
135
136 log::set_logger(LOGGER.get().unwrap())
137 .map(|()| log::set_max_level(filter))
138 .unwrap();
139
140 panic::set_hook(Box::new(move |panic_info| {
141 if filter == LevelFilter::Off {
142 return;
143 }
144
145 let line = if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
146 format!(
147 "{} {} {}",
148 get_formatted_timestamp(),
149 get_formatted_level("PANIC"),
150 s,
151 )
152 } else if let Some(s) = panic_info.payload().downcast_ref::<String>() {
153 format!(
154 "{} {} {}",
155 get_formatted_timestamp(),
156 get_formatted_level("PANIC"),
157 s,
158 )
159 } else {
160 format!(
161 "{} {} A panic occurred! Exitting...",
162 get_formatted_timestamp(),
163 get_formatted_level("PANIC"),
164 )
165 };
166
167 LOGGER
168 .get()
169 .unwrap()
170 .1
171 .send((OutputChannel::Error, line))
172 .ok();
173 }));
174}
175
176fn get_formatted_timestamp() -> String {
177 let now = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
178
179 let format = format_description!(
180 "[day]/[month]/[year] at [hour]:[minute]:[second].[subsecond digits:2]"
181 );
182
183 now.format(&format).unwrap().dimmed().to_string()
184}
185
186fn get_formatted_level(level: &str) -> String {
187 let string = format!("[{level}]");
188 let string = format!("{string:<7}");
189
190 match level {
191 "TRACE" => string.dimmed().to_string(),
192 "DEBUG" => string.white().to_string(),
193 "INFO" => string.blue().to_string(),
194 "WARN" => string.yellow().to_string(),
195 "ERROR" | "PANIC" => string.red().bold().to_string(),
196 _ => string.red().bold().to_string(),
197 }
198}