Support building `cfg=c_bindings` with `no-std`
[rust-lightning] / 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 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
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 core::cmp;
18 use core::fmt;
19
20 #[cfg(c_bindings)]
21 use prelude::*; // Needed for String
22
23 static LOG_LEVEL_NAMES: [&'static str; 6] = ["GOSSIP", "TRACE", "DEBUG", "INFO", "WARN", "ERROR"];
24
25 /// An enum representing the available verbosity levels of the logger.
26 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
27 pub enum Level {
28         /// Designates extremely verbose information, including gossip-induced messages
29         Gossip,
30         /// Designates very low priority, often extremely verbose, information
31         Trace,
32         /// Designates lower priority information
33         Debug,
34         /// Designates useful information
35         Info,
36         /// Designates hazardous situations
37         Warn,
38         /// Designates very serious errors
39         Error,
40 }
41
42 impl PartialOrd for Level {
43         #[inline]
44         fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
45                 Some(self.cmp(other))
46         }
47
48         #[inline]
49         fn lt(&self, other: &Level) -> bool {
50                 (*self as usize) < *other as usize
51         }
52
53         #[inline]
54         fn le(&self, other: &Level) -> bool {
55                 *self as usize <= *other as usize
56         }
57
58         #[inline]
59         fn gt(&self, other: &Level) -> bool {
60                 *self as usize > *other as usize
61         }
62
63         #[inline]
64         fn ge(&self, other: &Level) -> bool {
65                 *self as usize >= *other as usize
66         }
67 }
68
69 impl Ord for Level {
70         #[inline]
71         fn cmp(&self, other: &Level) -> cmp::Ordering {
72                 (*self as usize).cmp(&(*other as usize))
73         }
74 }
75
76 impl fmt::Display for Level {
77         fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
78                 fmt.pad(LOG_LEVEL_NAMES[*self as usize])
79         }
80 }
81
82 impl Level {
83         /// Returns the most verbose logging level.
84         #[inline]
85         pub fn max() -> Level {
86                 Level::Gossip
87         }
88 }
89
90 /// A Record, unit of logging output with Metadata to enable filtering
91 /// Module_path, file, line to inform on log's source
92 #[derive(Clone, Debug)]
93 pub struct Record<'a> {
94         /// The verbosity level of the message.
95         pub level: Level,
96         #[cfg(not(c_bindings))]
97         /// The message body.
98         pub args: fmt::Arguments<'a>,
99         #[cfg(c_bindings)]
100         /// The message body.
101         pub args: String,
102         /// The module path of the message.
103         pub module_path: &'static str,
104         /// The source file containing the message.
105         pub file: &'static str,
106         /// The line containing the message.
107         pub line: u32,
108
109         #[cfg(c_bindings)]
110         /// We don't actually use the lifetime parameter in C bindings (as there is no good way to
111         /// communicate a lifetime to a C, or worse, Java user).
112         _phantom: core::marker::PhantomData<&'a ()>,
113 }
114
115 impl<'a> Record<'a> {
116         /// Returns a new Record.
117         /// (C-not exported) as fmt can't be used in C
118         #[inline]
119         pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'static str, file: &'static str, line: u32) -> Record<'a> {
120                 Record {
121                         level,
122                         #[cfg(not(c_bindings))]
123                         args,
124                         #[cfg(c_bindings)]
125                         args: format!("{}", args),
126                         module_path,
127                         file,
128                         line,
129                         #[cfg(c_bindings)]
130                         _phantom: core::marker::PhantomData,
131                 }
132         }
133 }
134
135 /// A trait encapsulating the operations required of a logger
136 pub trait Logger {
137         /// Logs the `Record`
138         fn log(&self, record: &Record);
139 }
140
141 /// Wrapper for logging byte slices in hex format.
142 /// (C-not exported) as fmt can't be used in C
143 #[doc(hidden)]
144 pub struct DebugBytes<'a>(pub &'a [u8]);
145 impl<'a> core::fmt::Display for DebugBytes<'a> {
146         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
147                 for i in self.0 {
148                         write!(f, "{:02x}", i)?;
149                 }
150                 Ok(())
151         }
152 }
153
154 #[cfg(test)]
155 mod tests {
156         use util::logger::{Logger, Level};
157         use util::test_utils::TestLogger;
158         use sync::Arc;
159
160         #[test]
161         fn test_level_show() {
162                 assert_eq!("INFO", Level::Info.to_string());
163                 assert_eq!("ERROR", Level::Error.to_string());
164                 assert_ne!("WARN", Level::Error.to_string());
165         }
166
167         struct WrapperLog {
168                 logger: Arc<Logger>
169         }
170
171         impl WrapperLog {
172                 fn new(logger: Arc<Logger>) -> WrapperLog {
173                         WrapperLog {
174                                 logger,
175                         }
176                 }
177
178                 fn call_macros(&self) {
179                         log_error!(self.logger, "This is an error");
180                         log_warn!(self.logger, "This is a warning");
181                         log_info!(self.logger, "This is an info");
182                         log_debug!(self.logger, "This is a debug");
183                         log_trace!(self.logger, "This is a trace");
184                         log_gossip!(self.logger, "This is a gossip");
185                 }
186         }
187
188         #[test]
189         fn test_logging_macros() {
190                 let mut logger = TestLogger::new();
191                 logger.enable(Level::Gossip);
192                 let logger : Arc<Logger> = Arc::new(logger);
193                 let wrapper = WrapperLog::new(Arc::clone(&logger));
194                 wrapper.call_macros();
195         }
196
197         #[test]
198         fn test_log_ordering() {
199                 assert!(Level::Error > Level::Warn);
200                 assert!(Level::Error >= Level::Warn);
201                 assert!(Level::Error >= Level::Error);
202                 assert!(Level::Warn > Level::Info);
203                 assert!(Level::Warn >= Level::Info);
204                 assert!(Level::Warn >= Level::Warn);
205                 assert!(Level::Info > Level::Debug);
206                 assert!(Level::Info >= Level::Debug);
207                 assert!(Level::Info >= Level::Info);
208                 assert!(Level::Debug > Level::Trace);
209                 assert!(Level::Debug >= Level::Trace);
210                 assert!(Level::Debug >= Level::Debug);
211                 assert!(Level::Trace > Level::Gossip);
212                 assert!(Level::Trace >= Level::Gossip);
213                 assert!(Level::Trace >= Level::Trace);
214                 assert!(Level::Gossip >= Level::Gossip);
215
216                 assert!(Level::Error <= Level::Error);
217                 assert!(Level::Warn < Level::Error);
218                 assert!(Level::Warn <= Level::Error);
219                 assert!(Level::Warn <= Level::Warn);
220                 assert!(Level::Info < Level::Warn);
221                 assert!(Level::Info <= Level::Warn);
222                 assert!(Level::Info <= Level::Info);
223                 assert!(Level::Debug < Level::Info);
224                 assert!(Level::Debug <= Level::Info);
225                 assert!(Level::Debug <= Level::Debug);
226                 assert!(Level::Trace < Level::Debug);
227                 assert!(Level::Trace <= Level::Debug);
228                 assert!(Level::Trace <= Level::Trace);
229                 assert!(Level::Gossip < Level::Trace);
230                 assert!(Level::Gossip <= Level::Trace);
231                 assert!(Level::Gossip <= Level::Gossip);
232         }
233 }