diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/lib.rs | 76 | ||||
-rw-r--r-- | src/log_level.rs | 37 |
2 files changed, 113 insertions, 0 deletions
diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..e0386ab --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,76 @@ +mod log_level; +pub use log_level::*; + +use std::sync::Mutex; + + +pub const NORMAL: &str = "\x1b[0m"; +pub const BOLD: &str = "\x1b[1m"; +pub const WHITE: &str = "\x1b[37m"; +pub const RED: &str = "\x1b[31m"; +pub const YELLOW: &str = "\x1b[33m"; +pub const BLUE: &str = "\x1b[34m"; + + +pub 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() +} + + +#[macro_export] macro_rules! info { + ($($tokens:tt)*) => { + if *$crate::LOG_LEVEL.lock().unwrap() <= { LogLevel::Info } { + eprint!("{}{}[INFO]{}: ", + $crate::BOLD, + $crate::BLUE, + $crate::NORMAL, + ); + eprint!($($tokens)*); + eprintln!("{}", + $crate::NORMAL, + ); + } + }; +} + +#[macro_export] macro_rules! warn { + ($($tokens:tt)*) => {{ + if *$crate::LOG_LEVEL.lock().unwrap() <= { LogLevel::Warn } { + eprint!("{}{}[WARNING]{}{}: ", + $crate::BOLD, + $crate::YELLOW, + $crate::NORMAL, + $crate::WHITE, + ); + eprint!($($tokens)*); + eprintln!("{}", + $crate::NORMAL, + ); + } + }}; +} + +#[macro_export] macro_rules! error { + ($($tokens:tt)*) => {{ + if *$crate::LOG_LEVEL.lock().unwrap() <= { LogLevel::Error } { + eprint!("{}{}[ERROR]{}: ", + $crate::BOLD, + $crate::RED, + $crate::WHITE, + + ); + eprint!($($tokens)*); + eprintln!("{}", + $crate::NORMAL, + ); + } + std::process::exit(1); + }}; +} + diff --git a/src/log_level.rs b/src/log_level.rs new file mode 100644 index 0000000..6c84cb0 --- /dev/null +++ b/src/log_level.rs @@ -0,0 +1,37 @@ + +use std::cmp::Ordering; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LogLevel { + /// Verbose record of decisions and operations. + Info, + /// Report recoverable issues. + Warn, + /// Report unrecoverable errors and quit. + Error, +} + +impl PartialOrd for LogLevel { + fn partial_cmp(&self, other: &LogLevel) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for LogLevel { + fn cmp(&self, other: &LogLevel) -> Ordering { + use LogLevel::*; + match (self, other) { + (Info , Info ) => Ordering::Equal, + (Info , Warn ) => Ordering::Less, + (Info , Error) => Ordering::Less, + + (Warn , Info ) => Ordering::Greater, + (Warn , Warn ) => Ordering::Equal, + (Warn , Error) => Ordering::Less, + + (Error , Info ) => Ordering::Greater, + (Error , Warn ) => Ordering::Greater, + (Error , Error) => Ordering::Equal, + } + } +} |