Skip to main content

pretty_logging/
lib.rs

1//! A minimal and pretty logger for the [`log`] crate.
2//!
3//! To initialize it, call the [`init()`] function.
4//!
5//! ```
6//! use log::LevelFilter;
7//!
8//! pretty_logging::init(LevelFilter::Info, []);
9//!
10//! log::trace!("Hello pretty logger!");
11//! log::debug!("Hello pretty logger!");
12//! log::info!("Hello pretty logger!");
13//! log::warn!("Hello pretty logger!");
14//! log::error!("Hello pretty logger!");
15//! panic!("Hello pretty logger!");
16//! ```
17//!
18//! The [`init()`] function spawns a thread which reads all incoming log messages and writes them
19//! to the standard/error output.
20//!
21//! You should note that when using this logger, the [`init()`] function will set a custom panic
22//! hook, which will override any previous panic hooks set. If you use custom panic hooks, make
23//! sure to set them after [`init()`] is called.
24
25use 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
108/// Initializes the logger. This function spawns a thread to read log messages and write them to
109/// the appropriate output without blocking the current task.
110///
111/// This function also sets a custom panic hook to log panics. If you need to set a custom panic
112/// hook, set it after this function is called to prevent your custom hook from being overriden.
113///
114/// Once this function is called, you must avoid calling [`println!`] and [`eprintln!`].
115///
116/// Arguments:
117/// * `filter` - The level filter for the logger.
118/// * `modules` - A list of root module names which to log. An empty array will log all modules.
119///   You may want to set this to your crate's name, like `["my_crate_name"]`, to only display logs
120///   from your crate's modules.
121///
122/// Example:
123/// ```
124/// use log::LevelFilter;
125///
126/// // Displays all logs from all crates.
127/// pretty_logging::init(LevelFilter::Trace, []);
128/// ```
129pub 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}