forensic_rs/logging/
mod.rs

1use std::{
2    cell::RefCell, borrow::Cow, sync::atomic::{AtomicUsize, Ordering},
3};
4
5use crate::channel::{self, Receiver, Sender};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
8#[repr(usize)]
9pub enum Level {
10    Off,
11    Error,
12    Warn,
13    Info,
14    Debug,
15    Trace,
16}
17
18#[derive(Clone)]
19pub struct Logger {
20    pub channel : Sender<Message>
21}
22
23impl Default for Logger {
24    fn default() -> Self {
25        let (sender,_reveiver) = channel::channel();
26        Self { channel: sender }
27    }
28}
29impl Logger {
30    pub fn new(sender : Sender<Message>) -> Self {
31        Self {
32            channel : sender
33        }
34    }
35    pub fn log(&self, level : Level, module : &'static str, file : &'static str, line : u32, data : Cow<'static, str>) {
36        let _ = self.channel.send(Message { level, module, file, line, data });
37    }
38}
39
40#[derive(Debug, Clone)]
41pub struct Message {
42    pub level : Level,
43    pub module : &'static str,
44    pub line : u32,
45    pub file : &'static str,
46    pub data : Cow<'static, str>,
47}
48
49#[macro_use]
50pub mod macros;
51
52static MAX_NOTIFY_LEVEL_FILTER: AtomicUsize = AtomicUsize::new(5);
53//static NOTIFY_LEVEL_NAMES: [&str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
54
55#[inline]
56pub fn set_max_level(level: Level) {
57    MAX_NOTIFY_LEVEL_FILTER.store(level as usize, Ordering::Relaxed);
58}
59
60#[inline]
61pub fn enabled_level(level: &Level) -> bool {
62    MAX_NOTIFY_LEVEL_FILTER.load(Ordering::Relaxed) >= (*level as usize)
63}
64#[inline]
65pub fn max_level() -> Level {
66    unsafe { std::mem::transmute(MAX_NOTIFY_LEVEL_FILTER.load(Ordering::Relaxed)) }
67}
68
69thread_local! {
70    pub static COMPONENT_LOGGER : RefCell<Logger> = RefCell::new(Logger::default());
71}
72
73/// Initializes the logger for the current thread/component.
74pub fn initialize_logger(msngr: Logger) {
75    let _ = COMPONENT_LOGGER.with(|v| {
76        let mut brw = v.borrow_mut();
77        *brw = msngr;
78        Ok::<(), ()>(())
79    });
80    // Wait for local_key_cell_methods
81    //COMPONENT_LOGGER.replace(msngr);
82}
83
84/// Use for fast initialization during testing
85pub fn testing_logger_dummy() -> Receiver<Message> {
86    let (sender, receiver) = channel::channel();
87    let msngr = Logger::new(sender);
88    initialize_logger(msngr);
89    receiver
90}