Generate PaymentPathSuccessful event for each path
[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 static LOG_LEVEL_NAMES: [&'static str; 5] = ["TRACE", "DEBUG", "INFO", "WARN", "ERROR"];
21
22 /// An enum representing the available verbosity levels of the logger.
23 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
24 pub enum Level {
25         /// Designates very low priority, often extremely verbose, information
26         Trace,
27         /// Designates lower priority information
28         Debug,
29         /// Designates useful information
30         Info,
31         /// Designates hazardous situations
32         Warn,
33         /// Designates very serious errors
34         Error,
35 }
36
37 impl PartialOrd for Level {
38         #[inline]
39         fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
40                 Some(self.cmp(other))
41         }
42
43         #[inline]
44         fn lt(&self, other: &Level) -> bool {
45                 (*self as usize) < *other as usize
46         }
47
48         #[inline]
49         fn le(&self, other: &Level) -> bool {
50                 *self as usize <= *other as usize
51         }
52
53         #[inline]
54         fn gt(&self, other: &Level) -> bool {
55                 *self as usize > *other as usize
56         }
57
58         #[inline]
59         fn ge(&self, other: &Level) -> bool {
60                 *self as usize >= *other as usize
61         }
62 }
63
64 impl Ord for Level {
65         #[inline]
66         fn cmp(&self, other: &Level) -> cmp::Ordering {
67                 (*self as usize).cmp(&(*other as usize))
68         }
69 }
70
71 impl fmt::Display for Level {
72         fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
73                 fmt.pad(LOG_LEVEL_NAMES[*self as usize])
74         }
75 }
76
77 impl Level {
78         /// Returns the most verbose logging level.
79         #[inline]
80         pub fn max() -> Level {
81                 Level::Trace
82         }
83 }
84
85 /// A Record, unit of logging output with Metadata to enable filtering
86 /// Module_path, file, line to inform on log's source
87 /// (C-not exported) - we convert to a const char* instead
88 #[derive(Clone,Debug)]
89 pub struct Record<'a> {
90         /// The verbosity level of the message.
91         pub level: Level,
92         /// The message body.
93         pub args: fmt::Arguments<'a>,
94         /// The module path of the message.
95         pub module_path: &'a str,
96         /// The source file containing the message.
97         pub file: &'a str,
98         /// The line containing the message.
99         pub line: u32,
100 }
101
102 impl<'a> Record<'a> {
103         /// Returns a new Record.
104         /// (C-not exported) as fmt can't be used in C
105         #[inline]
106         pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'a str, file: &'a str, line: u32) -> Record<'a> {
107                 Record {
108                         level,
109                         args,
110                         module_path,
111                         file,
112                         line
113                 }
114         }
115 }
116
117 /// A trait encapsulating the operations required of a logger
118 pub trait Logger {
119         /// Logs the `Record`
120         fn log(&self, record: &Record);
121 }
122
123 /// Wrapper for logging byte slices in hex format.
124 /// (C-not exported) as fmt can't be used in C
125 #[doc(hidden)]
126 pub struct DebugBytes<'a>(pub &'a [u8]);
127 impl<'a> core::fmt::Display for DebugBytes<'a> {
128         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
129                 for i in self.0 {
130                         write!(f, "{:02x}", i)?;
131                 }
132                 Ok(())
133         }
134 }
135
136 #[cfg(test)]
137 mod tests {
138         use util::logger::{Logger, Level};
139         use util::test_utils::TestLogger;
140         use sync::Arc;
141
142         #[test]
143         fn test_level_show() {
144                 assert_eq!("INFO", Level::Info.to_string());
145                 assert_eq!("ERROR", Level::Error.to_string());
146                 assert_ne!("WARN", Level::Error.to_string());
147         }
148
149         struct WrapperLog {
150                 logger: Arc<Logger>
151         }
152
153         impl WrapperLog {
154                 fn new(logger: Arc<Logger>) -> WrapperLog {
155                         WrapperLog {
156                                 logger,
157                         }
158                 }
159
160                 fn call_macros(&self) {
161                         log_error!(self.logger, "This is an error");
162                         log_warn!(self.logger, "This is a warning");
163                         log_info!(self.logger, "This is an info");
164                         log_debug!(self.logger, "This is a debug");
165                         log_trace!(self.logger, "This is a trace");
166                 }
167         }
168
169         #[test]
170         fn test_logging_macros() {
171                 let mut logger = TestLogger::new();
172                 logger.enable(Level::Trace);
173                 let logger : Arc<Logger> = Arc::new(logger);
174                 let wrapper = WrapperLog::new(Arc::clone(&logger));
175                 wrapper.call_macros();
176         }
177
178         #[test]
179         fn test_log_ordering() {
180                 assert!(Level::Error > Level::Warn);
181                 assert!(Level::Error >= Level::Warn);
182                 assert!(Level::Error >= Level::Error);
183                 assert!(Level::Warn > Level::Info);
184                 assert!(Level::Warn >= Level::Info);
185                 assert!(Level::Warn >= Level::Warn);
186                 assert!(Level::Info > Level::Debug);
187                 assert!(Level::Info >= Level::Debug);
188                 assert!(Level::Info >= Level::Info);
189                 assert!(Level::Debug > Level::Trace);
190                 assert!(Level::Debug >= Level::Trace);
191                 assert!(Level::Debug >= Level::Debug);
192                 assert!(Level::Trace >= Level::Trace);
193
194                 assert!(Level::Error <= Level::Error);
195                 assert!(Level::Warn < Level::Error);
196                 assert!(Level::Warn <= Level::Error);
197                 assert!(Level::Warn <= Level::Warn);
198                 assert!(Level::Info < Level::Warn);
199                 assert!(Level::Info <= Level::Warn);
200                 assert!(Level::Info <= Level::Info);
201                 assert!(Level::Debug < Level::Info);
202                 assert!(Level::Debug <= Level::Info);
203                 assert!(Level::Debug <= Level::Debug);
204                 assert!(Level::Trace < Level::Debug);
205                 assert!(Level::Trace <= Level::Debug);
206                 assert!(Level::Trace <= Level::Trace);
207         }
208 }