msgs: Reformulate unknown bits calculation w/ any
[rust-lightning] / src / util / logger.rs
1 // Pruned copy of crate rust log, without global logger
2 // https://github.com/rust-lang-nursery/log #7a60286
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 //! Log traits live here, which are called throughout the library to provide useful information for
11 //! debugging purposes.
12 //!
13 //! There is currently 2 ways to filter log messages. First one, by using compilation features, e.g "max_level_off".
14 //! The second one, client-side by implementing check against Record Level field.
15 //! Each module may have its own Logger or share one.
16
17 use std::cmp;
18 use std::fmt;
19 use std::sync::Arc;
20
21 static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
22
23 /// An enum representing the available verbosity levels of the logger.
24 #[derive(Copy, Clone, Eq, Debug, Hash)]
25 pub enum Level {
26         ///Designates logger being silent
27         Off,
28         /// Designates very serious errors
29         Error,
30         /// Designates hazardous situations
31         Warn,
32         /// Designates useful information
33         Info,
34         /// Designates lower priority information
35         Debug,
36         /// Designates very low priority, often extremely verbose, information
37         Trace,
38 }
39
40 impl PartialEq for Level {
41         #[inline]
42         fn eq(&self, other: &Level) -> bool {
43                 *self as usize == *other as usize
44         }
45 }
46
47 impl PartialOrd for Level {
48         #[inline]
49         fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
50                 Some(self.cmp(other))
51         }
52
53         #[inline]
54         fn lt(&self, other: &Level) -> bool {
55                 (*self as usize) < *other as usize
56         }
57
58         #[inline]
59         fn le(&self, other: &Level) -> bool {
60                 *self as usize <= *other as usize
61         }
62
63         #[inline]
64         fn gt(&self, other: &Level) -> bool {
65                 *self as usize > *other as usize
66         }
67
68         #[inline]
69         fn ge(&self, other: &Level) -> bool {
70                 *self as usize >= *other as usize
71         }
72 }
73
74 impl Ord for Level {
75         #[inline]
76         fn cmp(&self, other: &Level) -> cmp::Ordering {
77                 (*self as usize).cmp(&(*other as usize))
78         }
79 }
80
81 impl fmt::Display for Level {
82         fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
83                 fmt.pad(LOG_LEVEL_NAMES[*self as usize])
84         }
85 }
86
87 impl Level {
88         /// Returns the most verbose logging level.
89         #[inline]
90         pub fn max() -> Level {
91                 Level::Trace
92         }
93 }
94
95 /// A Record, unit of logging output with Metadata to enable filtering
96 /// Module_path, file, line to inform on log's source
97 #[derive(Clone,Debug)]
98 pub struct Record<'a> {
99         /// The verbosity level of the message.
100         pub level: Level,
101         /// The message body.
102         pub args: fmt::Arguments<'a>,
103         /// The module path of the message.
104         pub module_path: &'a str,
105         /// The source file containing the message.
106         pub file: &'a str,
107         /// The line containing the message.
108         pub line: u32,
109 }
110
111 impl<'a> Record<'a> {
112         /// Returns a new Record.
113         #[inline]
114         pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'a str, file: &'a str, line: u32) -> Record<'a> {
115                 Record {
116                         level,
117                         args,
118                         module_path,
119                         file,
120                         line
121                 }
122         }
123 }
124
125 /// A trait encapsulating the operations required of a logger
126 pub trait Logger: Sync + Send {
127         /// Logs the `Record`
128         fn log(&self, record: &Record);
129 }
130
131 pub(crate) struct LogHolder<'a> { pub(crate) logger: &'a Arc<Logger> }
132
133 #[cfg(test)]
134 mod tests {
135         use util::logger::{Logger, Level};
136         use util::test_utils::TestLogger;
137         use std::sync::{Arc};
138
139         #[test]
140         fn test_level_show() {
141                 assert_eq!("INFO", Level::Info.to_string());
142                 assert_eq!("ERROR", Level::Error.to_string());
143                 assert_ne!("WARN", Level::Error.to_string());
144         }
145
146         struct WrapperLog {
147                 logger: Arc<Logger>
148         }
149
150         impl WrapperLog {
151                 fn new(logger: Arc<Logger>) -> WrapperLog {
152                         WrapperLog {
153                                 logger,
154                         }
155                 }
156
157                 fn call_macros(&self) {
158                         log_error!(self, "This is an error");
159                         log_warn!(self, "This is a warning");
160                         log_info!(self, "This is an info");
161                         log_debug!(self, "This is a debug");
162                         log_trace!(self, "This is a trace");
163                 }
164         }
165
166         #[test]
167         fn test_logging_macros() {
168                 let mut logger = TestLogger::new();
169                 logger.enable(Level::Trace);
170                 let logger : Arc<Logger> = Arc::new(logger);
171                 let wrapper = WrapperLog::new(Arc::clone(&logger));
172                 wrapper.call_macros();
173         }
174 }