Skip to main content

pretty_log/
log.rs

1use std::sync::Mutex;
2
3use colored::Colorize;
4
5use crate::PrettyError;
6
7pub static LOGGER: Mutex<Option<Logger>> = Mutex::new(None);
8// Customize the global logger so that it contains a title on every message
9//  
10// Example:
11// use pretty_log::log;
12//
13// log::init("MyApp");
14// log::info("Hello, world!");
15// log::warn("Something went wrong!");
16// log::error("Something went very wrong!");
17//
18// Output:
19// MyApp Hello, world!
20// MyApp Something went wrong!
21// MyApp Something went very wrong!
22pub struct Logger {
23    title: String,
24}
25
26pub fn message_prefix() -> String {
27    match LOGGER
28        .lock()
29        .expect_p("Could not acquire global Logger lock")
30        .as_ref()
31    {
32        Some(logger) => logger.title.clone(),
33        None => String::from(""),
34    }
35}
36
37pub fn init(title: &str) -> () {
38    LOGGER
39        .lock()
40        .expect_p("Could not acquire global Logger lock")
41        .replace(Logger {
42            title: format!("{} ", title),
43        });
44}
45
46pub fn info(message: &str) {
47    println!("{}{}", message_prefix().blue(), message.blue());
48}
49
50pub fn warn(message: &str) {
51    println!("{}{}", message_prefix().yellow(), message.yellow());
52}
53
54pub fn error(message: &str) {
55    println!("{}{}", message_prefix().red().bold(), message.red().bold());
56}
57
58pub fn error_exit(message: &str) -> ! {
59    println!("{}{}", message_prefix().red().bold(), message.red().bold());
60    std::process::exit(1);
61}