Merge pull request #1163 from TheBlueMatt/2021-11-support-insecure-counterparty
[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 #[derive(Clone, Debug)]
90 pub struct Record<'a> {
91         /// The verbosity level of the message.
92         pub level: Level,
93         #[cfg(not(c_bindings))]
94         /// The message body.
95         pub args: fmt::Arguments<'a>,
96         #[cfg(c_bindings)]
97         /// The message body.
98         pub args: String,
99         /// The module path of the message.
100         pub module_path: &'static str,
101         /// The source file containing the message.
102         pub file: &'static str,
103         /// The line containing the message.
104         pub line: u32,
105
106         #[cfg(c_bindings)]
107         /// We don't actually use the lifetime parameter in C bindings (as there is no good way to
108         /// communicate a lifetime to a C, or worse, Java user).
109         _phantom: core::marker::PhantomData<&'a ()>,
110 }
111
112 impl<'a> Record<'a> {
113         /// Returns a new Record.
114         /// (C-not exported) as fmt can't be used in C
115         #[inline]
116         pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'static str, file: &'static str, line: u32) -> Record<'a> {
117                 Record {
118                         level,
119                         #[cfg(not(c_bindings))]
120                         args,
121                         #[cfg(c_bindings)]
122                         args: format!("{}", args),
123                         module_path,
124                         file,
125                         line,
126                         #[cfg(c_bindings)]
127                         _phantom: core::marker::PhantomData,
128                 }
129         }
130 }
131
132 /// A trait encapsulating the operations required of a logger
133 pub trait Logger {
134         /// Logs the `Record`
135         fn log(&self, record: &Record);
136 }
137
138 /// Wrapper for logging byte slices in hex format.
139 /// (C-not exported) as fmt can't be used in C
140 #[doc(hidden)]
141 pub struct DebugBytes<'a>(pub &'a [u8]);
142 impl<'a> core::fmt::Display for DebugBytes<'a> {
143         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
144                 for i in self.0 {
145                         write!(f, "{:02x}", i)?;
146                 }
147                 Ok(())
148         }
149 }
150
151 #[cfg(test)]
152 mod tests {
153         use util::logger::{Logger, Level};
154         use util::test_utils::TestLogger;
155         use sync::Arc;
156
157         #[test]
158         fn test_level_show() {
159                 assert_eq!("INFO", Level::Info.to_string());
160                 assert_eq!("ERROR", Level::Error.to_string());
161                 assert_ne!("WARN", Level::Error.to_string());
162         }
163
164         struct WrapperLog {
165                 logger: Arc<Logger>
166         }
167
168         impl WrapperLog {
169                 fn new(logger: Arc<Logger>) -> WrapperLog {
170                         WrapperLog {
171                                 logger,
172                         }
173                 }
174
175                 fn call_macros(&self) {
176                         log_error!(self.logger, "This is an error");
177                         log_warn!(self.logger, "This is a warning");
178                         log_info!(self.logger, "This is an info");
179                         log_debug!(self.logger, "This is a debug");
180                         log_trace!(self.logger, "This is a trace");
181                         log_gossip!(self.logger, "This is a gossip");
182                 }
183         }
184
185         #[test]
186         fn test_logging_macros() {
187                 let mut logger = TestLogger::new();
188                 logger.enable(Level::Gossip);
189                 let logger : Arc<Logger> = Arc::new(logger);
190                 let wrapper = WrapperLog::new(Arc::clone(&logger));
191                 wrapper.call_macros();
192         }
193
194         #[test]
195         fn test_log_ordering() {
196                 assert!(Level::Error > Level::Warn);
197                 assert!(Level::Error >= Level::Warn);
198                 assert!(Level::Error >= Level::Error);
199                 assert!(Level::Warn > Level::Info);
200                 assert!(Level::Warn >= Level::Info);
201                 assert!(Level::Warn >= Level::Warn);
202                 assert!(Level::Info > Level::Debug);
203                 assert!(Level::Info >= Level::Debug);
204                 assert!(Level::Info >= Level::Info);
205                 assert!(Level::Debug > Level::Trace);
206                 assert!(Level::Debug >= Level::Trace);
207                 assert!(Level::Debug >= Level::Debug);
208                 assert!(Level::Trace > Level::Gossip);
209                 assert!(Level::Trace >= Level::Gossip);
210                 assert!(Level::Trace >= Level::Trace);
211                 assert!(Level::Gossip >= Level::Gossip);
212
213                 assert!(Level::Error <= Level::Error);
214                 assert!(Level::Warn < Level::Error);
215                 assert!(Level::Warn <= Level::Error);
216                 assert!(Level::Warn <= Level::Warn);
217                 assert!(Level::Info < Level::Warn);
218                 assert!(Level::Info <= Level::Warn);
219                 assert!(Level::Info <= Level::Info);
220                 assert!(Level::Debug < Level::Info);
221                 assert!(Level::Debug <= Level::Info);
222                 assert!(Level::Debug <= Level::Debug);
223                 assert!(Level::Trace < Level::Debug);
224                 assert!(Level::Trace <= Level::Debug);
225                 assert!(Level::Trace <= Level::Trace);
226                 assert!(Level::Gossip < Level::Trace);
227                 assert!(Level::Gossip <= Level::Trace);
228                 assert!(Level::Gossip <= Level::Gossip);
229         }
230 }