use std::fmt;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Level {
#[default]
Error = 1,
Warn = 2,
Info = 3,
Debug = 4,
Trace = 5,
}
impl Level {
pub const ALL: [Level; 5] = [Level::Error, Level::Warn, Level::Info, Level::Debug, Level::Trace];
pub fn name(self) -> &'static str {
match self {
Level::Error => "error",
Level::Warn => "warn",
Level::Info => "info",
Level::Debug => "debug",
Level::Trace => "trace",
}
}
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
type Sink = dyn Fn(Level, fmt::Arguments<'_>) + Send + Sync;
#[derive(Clone, Default)]
pub struct Log {
sink: Option<Arc<Sink>>,
level: Level,
}
impl Log {
pub fn new(level: Level, sink: impl Fn(Level, fmt::Arguments<'_>) + Send + Sync + 'static) -> Self {
Log { sink: Some(Arc::new(sink)), level }
}
pub fn none() -> Self {
Log::default()
}
pub fn level(&self) -> Option<Level> {
self.sink.as_ref().map(|_| self.level)
}
#[inline]
pub fn enabled(&self, level: Level) -> bool {
level <= self.level && self.sink.is_some()
}
#[inline]
pub fn write(&self, level: Level, message: fmt::Arguments<'_>) {
if let Some(sink) = &self.sink {
if level <= self.level {
sink(level, message);
}
}
}
}
impl fmt::Debug for Log {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Log").field("level", &self.level()).finish_non_exhaustive()
}
}
macro_rules! sb_log {
($log:expr, $level:ident, $($arg:tt)+) => {{
let log: &$crate::log::Log = $log;
if log.enabled($crate::log::Level::$level) {
log.write($crate::log::Level::$level, format_args!($($arg)+));
}
}};
}
pub(crate) use sb_log;
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Counted<'a>(&'a AtomicUsize);
impl fmt::Display for Counted<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fetch_add(1, Ordering::Relaxed);
f.write_str("counted")
}
}
#[test]
fn nothing_is_formatted_without_a_sink_or_above_its_level() {
let formatted = AtomicUsize::new(0);
let evaluated = AtomicUsize::new(0);
let arg = || {
evaluated.fetch_add(1, Ordering::Relaxed);
Counted(&formatted)
};
sb_log!(&Log::none(), Error, "{}", arg());
assert_eq!(Log::none().level(), None);
let lines = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&lines);
let log = Log::new(Level::Info, move |level, m| sink.lock().unwrap().push(format!("{level}: {m}")));
sb_log!(&log, Debug, "{}", arg());
sb_log!(&log, Trace, "{}", arg());
assert_eq!((formatted.load(Ordering::Relaxed), evaluated.load(Ordering::Relaxed)), (0, 0));
sb_log!(&log, Info, "{}", arg());
sb_log!(&log.clone(), Warn, "{} {}", arg(), 2);
assert_eq!((formatted.load(Ordering::Relaxed), evaluated.load(Ordering::Relaxed)), (2, 2));
assert_eq!(*lines.lock().unwrap(), ["info: counted", "warn: counted 2"]);
assert_eq!(log.level(), Some(Level::Info));
}
#[test]
fn levels_are_ordered_and_numbered() {
assert!(Level::ALL.windows(2).all(|w| w[0] < w[1]));
assert_eq!(Level::ALL.map(|l| l as i32), [1, 2, 3, 4, 5]);
}
}