Add intermediate `ConstructedTransaction`
[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 use core::ops::Deref;
22
23 use crate::ln::ChannelId;
24 #[cfg(c_bindings)]
25 use crate::prelude::*; // Needed for String
26
27 static LOG_LEVEL_NAMES: [&'static str; 6] = ["GOSSIP", "TRACE", "DEBUG", "INFO", "WARN", "ERROR"];
28
29 /// An enum representing the available verbosity levels of the logger.
30 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
31 pub enum Level {
32         /// Designates extremely verbose information, including gossip-induced messages
33         Gossip,
34         /// Designates very low priority, often extremely verbose, information
35         Trace,
36         /// Designates lower priority information
37         Debug,
38         /// Designates useful information
39         Info,
40         /// Designates hazardous situations
41         Warn,
42         /// Designates very serious errors
43         Error,
44 }
45
46 impl PartialOrd for Level {
47         #[inline]
48         fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
49                 Some(self.cmp(other))
50         }
51
52         #[inline]
53         fn lt(&self, other: &Level) -> bool {
54                 (*self as usize) < *other as usize
55         }
56
57         #[inline]
58         fn le(&self, other: &Level) -> bool {
59                 *self as usize <= *other as usize
60         }
61
62         #[inline]
63         fn gt(&self, other: &Level) -> bool {
64                 *self as usize > *other as usize
65         }
66
67         #[inline]
68         fn ge(&self, other: &Level) -> bool {
69                 *self as usize >= *other as usize
70         }
71 }
72
73 impl Ord for Level {
74         #[inline]
75         fn cmp(&self, other: &Level) -> cmp::Ordering {
76                 (*self as usize).cmp(&(*other as usize))
77         }
78 }
79
80 impl fmt::Display for Level {
81         fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
82                 fmt.pad(LOG_LEVEL_NAMES[*self as usize])
83         }
84 }
85
86 impl Level {
87         /// Returns the most verbose logging level.
88         #[inline]
89         pub fn max() -> Level {
90                 Level::Gossip
91         }
92 }
93
94 macro_rules! impl_record {
95         ($($args: lifetime)?, $($nonstruct_args: lifetime)?) => {
96 /// A Record, unit of logging output with Metadata to enable filtering
97 /// Module_path, file, line to inform on log's source
98 #[derive(Clone, Debug)]
99 pub struct Record<$($args)?> {
100         /// The verbosity level of the message.
101         pub level: Level,
102         /// The node id of the peer pertaining to the logged record.
103         ///
104         /// Note that in some cases a [`Self::channel_id`] may be filled in but this may still be
105         /// `None`, depending on if the peer information is readily available in LDK when the log is
106         /// generated.
107         pub peer_id: Option<PublicKey>,
108         /// The channel id of the channel pertaining to the logged record. May be a temporary id before
109         /// the channel has been funded.
110         pub channel_id: Option<ChannelId>,
111         #[cfg(not(c_bindings))]
112         /// The message body.
113         pub args: fmt::Arguments<'a>,
114         #[cfg(c_bindings)]
115         /// The message body.
116         pub args: String,
117         /// The module path of the message.
118         pub module_path: &'static str,
119         /// The source file containing the message.
120         pub file: &'static str,
121         /// The line containing the message.
122         pub line: u32,
123 }
124
125 impl<$($args)?> Record<$($args)?> {
126         /// Returns a new Record.
127         ///
128         /// This is not exported to bindings users as fmt can't be used in C
129         #[inline]
130         pub fn new<$($nonstruct_args)?>(
131                 level: Level, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>,
132                 args: fmt::Arguments<'a>, module_path: &'static str, file: &'static str, line: u32
133         ) -> Record<$($args)?> {
134                 Record {
135                         level,
136                         peer_id,
137                         channel_id,
138                         #[cfg(not(c_bindings))]
139                         args,
140                         #[cfg(c_bindings)]
141                         args: format!("{}", args),
142                         module_path,
143                         file,
144                         line,
145                 }
146         }
147 }
148 } }
149 #[cfg(not(c_bindings))]
150 impl_record!('a, );
151 #[cfg(c_bindings)]
152 impl_record!(, 'a);
153
154 /// A trait encapsulating the operations required of a logger.
155 pub trait Logger {
156         /// Logs the [`Record`].
157         fn log(&self, record: Record);
158 }
159
160 /// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`].
161 ///
162 /// This is not exported to bindings users as lifetimes are problematic and there's little reason
163 /// for this to be used downstream anyway.
164 pub struct WithContext<'a, L: Deref> where L::Target: Logger {
165         /// The logger to delegate to after adding context to the record.
166         logger: &'a L,
167         /// The node id of the peer pertaining to the logged record.
168         peer_id: Option<PublicKey>,
169         /// The channel id of the channel pertaining to the logged record.
170         channel_id: Option<ChannelId>,
171 }
172
173 impl<'a, L: Deref> Logger for WithContext<'a, L> where L::Target: Logger {
174         fn log(&self, mut record: Record) {
175                 if self.peer_id.is_some() {
176                         record.peer_id = self.peer_id
177                 };
178                 if self.channel_id.is_some() {
179                         record.channel_id = self.channel_id;
180                 }
181                 self.logger.log(record)
182         }
183 }
184
185 impl<'a, L: Deref> WithContext<'a, L> where L::Target: Logger {
186         /// Wraps the given logger, providing additional context to any logged records.
187         pub fn from(logger: &'a L, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>) -> Self {
188                 WithContext {
189                         logger,
190                         peer_id,
191                         channel_id,
192                 }
193         }
194 }
195
196 /// Wrapper for logging a [`PublicKey`] in hex format.
197 ///
198 /// This is not exported to bindings users as fmt can't be used in C
199 #[doc(hidden)]
200 pub struct DebugPubKey<'a>(pub &'a PublicKey);
201 impl<'a> core::fmt::Display for DebugPubKey<'a> {
202         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
203                 for i in self.0.serialize().iter() {
204                         write!(f, "{:02x}", i)?;
205                 }
206                 Ok(())
207         }
208 }
209
210 /// Wrapper for logging byte slices in hex format.
211 ///
212 /// This is not exported to bindings users as fmt can't be used in C
213 #[doc(hidden)]
214 pub struct DebugBytes<'a>(pub &'a [u8]);
215 impl<'a> core::fmt::Display for DebugBytes<'a> {
216         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
217                 for i in self.0 {
218                         write!(f, "{:02x}", i)?;
219                 }
220                 Ok(())
221         }
222 }
223
224 /// Wrapper for logging `Iterator`s.
225 ///
226 /// This is not exported to bindings users as fmt can't be used in C
227 #[doc(hidden)]
228 pub struct DebugIter<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone>(pub I);
229 impl<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone> fmt::Display for DebugIter<T, I> {
230         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
231                 write!(f, "[")?;
232                 let mut iter = self.0.clone();
233                 if let Some(item) = iter.next() {
234                         write!(f, "{}", item)?;
235                 }
236                 while let Some(item) = iter.next() {
237                         write!(f, ", {}", item)?;
238                 }
239                 write!(f, "]")?;
240                 Ok(())
241         }
242 }
243
244 #[cfg(test)]
245 mod tests {
246         use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
247         use crate::ln::ChannelId;
248         use crate::util::logger::{Logger, Level, WithContext};
249         use crate::util::test_utils::TestLogger;
250         use crate::sync::Arc;
251
252         #[test]
253         fn test_level_show() {
254                 assert_eq!("INFO", Level::Info.to_string());
255                 assert_eq!("ERROR", Level::Error.to_string());
256                 assert_ne!("WARN", Level::Error.to_string());
257         }
258
259         struct WrapperLog {
260                 logger: Arc<dyn Logger>
261         }
262
263         impl WrapperLog {
264                 fn new(logger: Arc<dyn Logger>) -> WrapperLog {
265                         WrapperLog {
266                                 logger,
267                         }
268                 }
269
270                 fn call_macros(&self) {
271                         log_error!(self.logger, "This is an error");
272                         log_warn!(self.logger, "This is a warning");
273                         log_info!(self.logger, "This is an info");
274                         log_debug!(self.logger, "This is a debug");
275                         log_trace!(self.logger, "This is a trace");
276                         log_gossip!(self.logger, "This is a gossip");
277                 }
278         }
279
280         #[test]
281         fn test_logging_macros() {
282                 let mut logger = TestLogger::new();
283                 logger.enable(Level::Gossip);
284                 let logger : Arc<dyn Logger> = Arc::new(logger);
285                 let wrapper = WrapperLog::new(Arc::clone(&logger));
286                 wrapper.call_macros();
287         }
288
289         #[test]
290         fn test_logging_with_context() {
291                 let logger = &TestLogger::new();
292                 let secp_ctx = Secp256k1::new();
293                 let pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
294                 let context_logger = WithContext::from(&logger, Some(pk), Some(ChannelId([0; 32])));
295                 log_error!(context_logger, "This is an error");
296                 log_warn!(context_logger, "This is an error");
297                 log_debug!(context_logger, "This is an error");
298                 log_trace!(context_logger, "This is an error");
299                 log_gossip!(context_logger, "This is an error");
300                 log_info!(context_logger, "This is an error");
301                 logger.assert_log_context_contains(
302                         "lightning::util::logger::tests", Some(pk), Some(ChannelId([0;32])), 6
303                 );
304         }
305
306         #[test]
307         fn test_logging_with_multiple_wrapped_context() {
308                 let logger = &TestLogger::new();
309                 let secp_ctx = Secp256k1::new();
310                 let pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
311                 let context_logger = &WithContext::from(&logger, None, Some(ChannelId([0; 32])));
312                 let full_context_logger = WithContext::from(&context_logger, Some(pk), None);
313                 log_error!(full_context_logger, "This is an error");
314                 log_warn!(full_context_logger, "This is an error");
315                 log_debug!(full_context_logger, "This is an error");
316                 log_trace!(full_context_logger, "This is an error");
317                 log_gossip!(full_context_logger, "This is an error");
318                 log_info!(full_context_logger, "This is an error");
319                 logger.assert_log_context_contains(
320                         "lightning::util::logger::tests", Some(pk), Some(ChannelId([0;32])), 6
321                 );
322         }
323
324         #[test]
325         fn test_log_ordering() {
326                 assert!(Level::Error > Level::Warn);
327                 assert!(Level::Error >= Level::Warn);
328                 assert!(Level::Error >= Level::Error);
329                 assert!(Level::Warn > Level::Info);
330                 assert!(Level::Warn >= Level::Info);
331                 assert!(Level::Warn >= Level::Warn);
332                 assert!(Level::Info > Level::Debug);
333                 assert!(Level::Info >= Level::Debug);
334                 assert!(Level::Info >= Level::Info);
335                 assert!(Level::Debug > Level::Trace);
336                 assert!(Level::Debug >= Level::Trace);
337                 assert!(Level::Debug >= Level::Debug);
338                 assert!(Level::Trace > Level::Gossip);
339                 assert!(Level::Trace >= Level::Gossip);
340                 assert!(Level::Trace >= Level::Trace);
341                 assert!(Level::Gossip >= Level::Gossip);
342
343                 assert!(Level::Error <= Level::Error);
344                 assert!(Level::Warn < Level::Error);
345                 assert!(Level::Warn <= Level::Error);
346                 assert!(Level::Warn <= Level::Warn);
347                 assert!(Level::Info < Level::Warn);
348                 assert!(Level::Info <= Level::Warn);
349                 assert!(Level::Info <= Level::Info);
350                 assert!(Level::Debug < Level::Info);
351                 assert!(Level::Debug <= Level::Info);
352                 assert!(Level::Debug <= Level::Debug);
353                 assert!(Level::Trace < Level::Debug);
354                 assert!(Level::Trace <= Level::Debug);
355                 assert!(Level::Trace <= Level::Trace);
356                 assert!(Level::Gossip < Level::Trace);
357                 assert!(Level::Gossip <= Level::Trace);
358                 assert!(Level::Gossip <= Level::Gossip);
359         }
360 }