summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 94b06f1b998ad44bbb951a7be58272ce08a59616 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
mod log_level;
pub use log_level::*;

use inked::*;

use std::sync::Mutex;


static LOG_LEVEL: Mutex<LogLevel> = Mutex::new(LogLevel::Warn);


pub fn set_log_level(level: LogLevel) {
    *LOG_LEVEL.lock().unwrap() = level;
}

pub fn get_log_level() -> LogLevel {
    *LOG_LEVEL.lock().unwrap()
}


pub fn log_info(message: &str, details: Option<impl Into<InkedString>>) {
    if *LOG_LEVEL.lock().unwrap() <= LogLevel::Info {
        let mut string = InkedString::new();
        string.push(ink!("[INFO]").blue().bold());
        string.push(ink!(": {message}\n"));
        if let Some(details) = details {
            string.append(details.into());
        }
        string.eprint();
    }
}

pub fn log_warn(message: &str, details: Option<impl Into<InkedString>>) {
    if *LOG_LEVEL.lock().unwrap() <= LogLevel::Warn {
        let mut string = InkedString::new();
        string.push(ink!("[WARN]").yellow().bold());
        string.push(ink!(": {message}\n").white());
        if let Some(details) = details {
            string.append(details.into());
        }
        string.eprint();
    }
}

pub fn log_error(message: &str, details: Option<impl Into<InkedString>>) {
    if *LOG_LEVEL.lock().unwrap() <= LogLevel::Error {
        let mut string = InkedString::new();
        string.push(ink!("[ERROR]").red().bold());
        string.push(ink!(": {message}\n").white());
        if let Some(details) = details {
            string.append(details.into());
        }
        string.eprint();
    }
}

pub fn log_fatal(message: &str, details: Option<impl Into<InkedString>>) -> ! {
    if *LOG_LEVEL.lock().unwrap() <= LogLevel::Fatal {
        let mut string = InkedString::new();
        string.push(ink!("[FATAL]").red().bold());
        string.push(ink!(": {message}\n").white());
        if let Some(details) = details {
            string.append(details.into());
        }
        string.eprint();
    }
    std::process::exit(1);
}

#[macro_export] macro_rules! info {
    ($($tokens:tt)*) => { $crate::log_info(&format!($($tokens)*), Option::<String>::None) };
}
#[macro_export] macro_rules! warn {
    ($($tokens:tt)*) => { $crate::log_warn(&format!($($tokens)*), Option::<String>::None) };
}
#[macro_export] macro_rules! error {
    ($($tokens:tt)*) => { $crate::log_error(&format!($($tokens)*), Option::<String>::None) };
}
#[macro_export] macro_rules! fatal {
    ($($tokens:tt)*) => { $crate::log_fatal(&format!($($tokens)*), Option::<String>::None) };
}