starina_api/
log.rs

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//! Logging utilities.
//!
//! [`std::println!`](https://doc.rust-lang.org/std/macro.println.html)
//! for Starina applications.
//!
//! # Format string syntax
//!
//! See [`std::fmt`](https://doc.rust-lang.org/std/fmt/index.html) for the
//! format syntax.
//!
//! # Examples
//!
//! ```
//! use starina_api::prelude::*; // Import all logging macros.
//!
//! info!("Hello, world!");
//!
//! let answer = 42;
//! debug!("The answer is {}", answer);
//! ```

/// The log level.
#[derive(Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
pub enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

/// Logs a message.
#[macro_export]
macro_rules! log {
    ($level:expr, $($arg:tt)+) => {{
        use $crate::log::LogLevel;

        if cfg!(debug_assertions) || $level <= LogLevel::Info {
            const RESET_COLOR: &str = "\x1b[0m";
            let (color, level_str) = match $level {
                LogLevel::Error => ("\x1b[91m", "ERR"),
                LogLevel::Warn =>  ("\x1b[33m", "WARN"),
                LogLevel::Info =>  ("\x1b[96m", "INFO"),
                LogLevel::Debug => ("\x1b[0m", "DEBUG"),
                LogLevel::Trace => ("\x1b[0m", "TRACE"),
            };

            $crate::println!(
                "[{:12}] {}{:6}{} {}",
                ::core::module_path!(),
                color,
                level_str,
                RESET_COLOR,
                format_args!($($arg)+)
            );
        }
    }};
}

/// Logs with [`LogLevel::Error`].
#[macro_export]
macro_rules! error {
    ($($arg:tt)+) => { $crate::log!($crate::log::LogLevel::Error, $($arg)+) }
}

/// Logs with [`LogLevel::Warn`].
#[macro_export]
macro_rules! warn {
    ($($arg:tt)+) => { $crate::log!($crate::log::LogLevel::Warn, $($arg)+) }
}

/// Logs with [`LogLevel::Info`].
#[macro_export]
macro_rules! info {
    ($($arg:tt)+) => { $crate::log!($crate::log::LogLevel::Info, $($arg)+) }
}

/// Logs with [`LogLevel::Debug`].
#[macro_export]
macro_rules! debug {
    ($($arg:tt)+) => { $crate::log!($crate::log::LogLevel::Debug, $($arg)+) }
}

/// Logs with [`LogLevel::Trace`].
#[macro_export]
macro_rules! trace {
    ($($arg:tt)+) => { $crate::log!($crate::log::LogLevel::Trace, $($arg)+) }
}

/// Similar to [`warn!`], but only logs in debug mode.
#[macro_export]
macro_rules! debug_warn {
    ($($arg:tt)+) => {
        if cfg!(debug_assertions) {
            $crate::warn!($($arg)+);
        }
    };
}