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