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