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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use std::fmt::Display;

struct Logger {
    to: Option<Box<dyn std::io::Write>>,
}
static mut LOGGER: Logger = Logger { to: None };
#[derive(PartialEq, PartialOrd, Copy, Clone)]
pub enum Level {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}
static mut LEVEL: Level = Level::Info;

impl Logger {
    /// Logs a message at the specified level.
    pub fn log(&mut self, level: Level, s: impl Display) {
        if level < unsafe { LEVEL } {
            return;
        }
        if let Some(ref mut to) = self.to {
            let _ = to
                .write(
                    match level {
                        Level::Trace => format!("[TRACE] {}\n", s),
                        Level::Debug => format!("[DEBUG] {}\n", s),
                        Level::Info => format!("[INFO] {}\n", s),
                        Level::Warn => format!("[WARN] {}\n", s),
                        Level::Error => format!("[ERROR] {}\n", s),
                    }
                    .as_bytes(),
                )
                .unwrap();
        }
        // self.to.write(b"\n").unwrap();
    }
}
/// Initializes the logger.
///
/// # Examples
///
/// ```
/// use xlog_rs::log;
/// log::init(std::io::stdout(), log::Level::Trace);
/// ```
pub fn init(to: impl std::io::Write + 'static, level: Level) {
    // Box::new(to);
    unsafe {
        LOGGER = Logger {
            to: Some(Box::new(to)),
        };
        LEVEL = level;
    }
}
/// Initializes the logger with a filename.
pub fn with_file(name: &str) {
    // Box::new(to);
    unsafe {
        LOGGER = Logger {
            to: Some(Box::new(
                std::fs::File::options()
                    .create(true)
                    .append(true)
                    .open(name.to_string())
                    .unwrap(),
            )),
        };
    }
}
/// Sets the log level.
///
/// # Examples
///
/// ```
/// use xlog_rs::log;
/// log::set_level(log::Level::Trace);
/// ```
pub fn set_level(level: Level) {
    unsafe {
        LEVEL = level;
    }
}
/// Returns the current log level.
pub fn level() -> Level {
    unsafe { LEVEL }
}
/// Logs a message at the specified level.
///
/// #Example
///
/// ```
/// use xlog_rs::log;
/// log::init(std::io::stdout(), log::Level::Trace);
/// log::log(log::Level::Debug,"abc");
/// ```
pub fn log(level: Level, msg: impl Display) {
    unsafe {
        LOGGER.log(level, msg);
    }
}
///
pub fn log_opt<T, F>(level: Level, value: Option<T>, map: F, msg: impl Display)
where
    F: Fn(T),
{
    match value {
        Some(value) => map(value),
        None => log(level, msg),
    }
}
///
pub fn log_res<T, E, F>(level: Level, value: Result<T, E>, map: F)
where
    E: Display,
    F: Fn(T),
{
    match value {
        Ok(value) => map(value),
        Err(e) => log(level, e.to_string()),
    }
}
/// Dispatch message with the type and level
#[macro_export]
macro_rules! log_dispatch {
    ($level:ident $msg:expr) => {
        $crate::log::log($crate::log::Level::$level, $msg);
    };
    ($level:ident opt,$val:expr,$map:expr,$msg:expr) => {
        $crate::log::log_opt($crate::log::Level::$level, $val, $map, $msg);
    };
    ($level:ident res,$val:expr,$map:expr) => {
        $crate::log::log_res($crate::log::Level::$level, $val, $map);
    };
}
/// Logs a message at the trace level.
///
/// #Example
///
/// ```
/// use xlog_rs::log;
/// log::init(std::io::stdout(), log::Level::Trace);
/// xlog_rs::trace!("abc");
/// let mut some = Some(());
/// xlog_rs::trace!(opt, some, |_| { xlog_rs::trace!("some") }, "none");
/// some = None;
/// xlog_rs::trace!(opt, some, |_| { xlog_rs::trace!("some") }, "none");
/// let mut ok = Ok(());
/// xlog_rs::trace!(res, ok, |_| { xlog_rs::trace!("ok") });
/// ok = Err("error");
/// xlog_rs::trace!(res, ok, |_| { xlog_rs::trace!("opt") });
/// ```
#[macro_export]
macro_rules! trace {
    ($($tail:tt)*) => {
        $crate::log_dispatch!(Trace $($tail)*);
    };
}
/// Logs a message at the debug level.
#[macro_export]
macro_rules! debug {
    ($($tail:tt)*) => {
        $crate::log_dispatch!(Debug $($tail)*);
    };
}
/// Logs a message at the info level.
#[macro_export]
macro_rules! info {
    ($($tail:tt)*) => {
        $crate::log_dispatch!(Info $($tail)*);
    };
}
/// Logs a message at the warn level.
#[macro_export]
macro_rules! warn {
    ($($tail:tt)*) => {
        $crate::log_dispatch!(Warn $($tail)*);
    };
}
/// Logs a message at the error level.
#[macro_export]
macro_rules! error {
    ($($tail:tt)*) => {
        $crate::log_dispatch!(Error $($tail)*);
    };
}