Add WithContext and Tests
[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 /// A Record, unit of logging output with Metadata to enable filtering
95 /// Module_path, file, line to inform on log's source
96 #[derive(Clone, Debug)]
97 pub struct Record<'a> {
98         /// The verbosity level of the message.
99         pub level: Level,
100         /// The node id of the peer pertaining to the logged record.
101         pub peer_id: Option<PublicKey>,
102         /// The channel id of the channel pertaining to the logged record. May be a temporary id before
103         /// the channel has been funded.
104         pub channel_id: Option<ChannelId>,
105         #[cfg(not(c_bindings))]
106         /// The message body.
107         pub args: fmt::Arguments<'a>,
108         #[cfg(c_bindings)]
109         /// The message body.
110         pub args: String,
111         /// The module path of the message.
112         pub module_path: &'static str,
113         /// The source file containing the message.
114         pub file: &'static str,
115         /// The line containing the message.
116         pub line: u32,
117
118         #[cfg(c_bindings)]
119         /// We don't actually use the lifetime parameter in C bindings (as there is no good way to
120         /// communicate a lifetime to a C, or worse, Java user).
121         _phantom: core::marker::PhantomData<&'a ()>,
122 }
123
124 impl<'a> Record<'a> {
125         /// Returns a new Record.
126         ///
127         /// This is not exported to bindings users as fmt can't be used in C
128         #[inline]
129         pub fn new(
130                 level: Level, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>,
131                 args: fmt::Arguments<'a>, module_path: &'static str, file: &'static str, line: u32
132         ) -> Record<'a> {
133                 Record {
134                         level,
135                         peer_id,
136                         channel_id,
137                         #[cfg(not(c_bindings))]
138                         args,
139                         #[cfg(c_bindings)]
140                         args: format!("{}", args),
141                         module_path,
142                         file,
143                         line,
144                         #[cfg(c_bindings)]
145                         _phantom: core::marker::PhantomData,
146                 }
147         }
148 }
149
150 /// A trait encapsulating the operations required of a logger.
151 pub trait Logger {
152         /// Logs the [`Record`].
153         fn log(&self, record: Record);
154 }
155
156 /// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`].
157 pub struct WithContext<'a, L: Deref> where L::Target: Logger {
158         /// The logger to delegate to after adding context to the record.
159         logger: &'a L,
160         /// The node id of the peer pertaining to the logged record.
161         peer_id: Option<PublicKey>,
162         /// The channel id of the channel pertaining to the logged record.
163         channel_id: Option<ChannelId>,
164 }
165
166 impl<'a, L: Deref> Logger for WithContext<'a, L> where L::Target: Logger {
167         fn log(&self, mut record: Record) {
168                 if self.peer_id.is_some() {
169                         record.peer_id = self.peer_id
170                 };
171                 if self.channel_id.is_some() {
172                         record.channel_id = self.channel_id;
173                 }
174                 self.logger.log(record)
175         }
176 }
177
178 impl<'a, L: Deref> WithContext<'a, L> where L::Target: Logger {
179         /// Wraps the given logger, providing additional context to any logged records.
180         pub fn from(logger: &'a L, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>) -> Self {
181                 WithContext {
182                         logger,
183                         peer_id,
184                         channel_id,
185                 }
186         }
187 }
188
189 /// Wrapper for logging a [`PublicKey`] in hex format.
190 ///
191 /// This is not exported to bindings users as fmt can't be used in C
192 #[doc(hidden)]
193 pub struct DebugPubKey<'a>(pub &'a PublicKey);
194 impl<'a> core::fmt::Display for DebugPubKey<'a> {
195         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
196                 for i in self.0.serialize().iter() {
197                         write!(f, "{:02x}", i)?;
198                 }
199                 Ok(())
200         }
201 }
202
203 /// Wrapper for logging byte slices in hex format.
204 ///
205 /// This is not exported to bindings users as fmt can't be used in C
206 #[doc(hidden)]
207 pub struct DebugBytes<'a>(pub &'a [u8]);
208 impl<'a> core::fmt::Display for DebugBytes<'a> {
209         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
210                 for i in self.0 {
211                         write!(f, "{:02x}", i)?;
212                 }
213                 Ok(())
214         }
215 }
216
217 /// Wrapper for logging `Iterator`s.
218 ///
219 /// This is not exported to bindings users as fmt can't be used in C
220 #[doc(hidden)]
221 pub struct DebugIter<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone>(pub I);
222 impl<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone> fmt::Display for DebugIter<T, I> {
223         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
224                 write!(f, "[")?;
225                 let mut iter = self.0.clone();
226                 if let Some(item) = iter.next() {
227                         write!(f, "{}", item)?;
228                 }
229                 while let Some(item) = iter.next() {
230                         write!(f, ", {}", item)?;
231                 }
232                 write!(f, "]")?;
233                 Ok(())
234         }
235 }
236
237 #[cfg(test)]
238 mod tests {
239         use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
240         use crate::ln::ChannelId;
241         use crate::util::logger::{Logger, Level, WithContext};
242         use crate::util::test_utils::TestLogger;
243         use crate::sync::Arc;
244
245         #[test]
246         fn test_level_show() {
247                 assert_eq!("INFO", Level::Info.to_string());
248                 assert_eq!("ERROR", Level::Error.to_string());
249                 assert_ne!("WARN", Level::Error.to_string());
250         }
251
252         struct WrapperLog {
253                 logger: Arc<Logger>
254         }
255
256         impl WrapperLog {
257                 fn new(logger: Arc<Logger>) -> WrapperLog {
258                         WrapperLog {
259                                 logger,
260                         }
261                 }
262
263                 fn call_macros(&self) {
264                         log_error!(self.logger, "This is an error");
265                         log_warn!(self.logger, "This is a warning");
266                         log_info!(self.logger, "This is an info");
267                         log_debug!(self.logger, "This is a debug");
268                         log_trace!(self.logger, "This is a trace");
269                         log_gossip!(self.logger, "This is a gossip");
270                 }
271         }
272
273         #[test]
274         fn test_logging_macros() {
275                 let mut logger = TestLogger::new();
276                 logger.enable(Level::Gossip);
277                 let logger : Arc<Logger> = Arc::new(logger);
278                 let wrapper = WrapperLog::new(Arc::clone(&logger));
279                 wrapper.call_macros();
280         }
281
282         #[test]
283         fn test_logging_with_context() {
284                 let logger = &TestLogger::new();
285                 let secp_ctx = Secp256k1::new();
286                 let pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
287                 let context_logger = WithContext::from(&logger, Some(pk), Some(ChannelId([0; 32])));
288                 log_error!(context_logger, "This is an error");
289                 log_warn!(context_logger, "This is an error");
290                 log_debug!(context_logger, "This is an error");
291                 log_trace!(context_logger, "This is an error");
292                 log_gossip!(context_logger, "This is an error");
293                 log_info!(context_logger, "This is an error");
294                 logger.assert_log_context_contains(
295                         "lightning::util::logger::tests", Some(pk), Some(ChannelId([0;32])), 6
296                 );
297         }
298
299         #[test]
300         fn test_logging_with_multiple_wrapped_context() {
301                 let logger = &TestLogger::new();
302                 let secp_ctx = Secp256k1::new();
303                 let pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
304                 let context_logger = &WithContext::from(&logger, None, Some(ChannelId([0; 32])));
305                 let full_context_logger = WithContext::from(&context_logger, Some(pk), None);
306                 log_error!(full_context_logger, "This is an error");
307                 log_warn!(full_context_logger, "This is an error");
308                 log_debug!(full_context_logger, "This is an error");
309                 log_trace!(full_context_logger, "This is an error");
310                 log_gossip!(full_context_logger, "This is an error");
311                 log_info!(full_context_logger, "This is an error");
312                 logger.assert_log_context_contains(
313                         "lightning::util::logger::tests", Some(pk), Some(ChannelId([0;32])), 6
314                 );
315         }
316
317         #[test]
318         fn test_log_ordering() {
319                 assert!(Level::Error > Level::Warn);
320                 assert!(Level::Error >= Level::Warn);
321                 assert!(Level::Error >= Level::Error);
322                 assert!(Level::Warn > Level::Info);
323                 assert!(Level::Warn >= Level::Info);
324                 assert!(Level::Warn >= Level::Warn);
325                 assert!(Level::Info > Level::Debug);
326                 assert!(Level::Info >= Level::Debug);
327                 assert!(Level::Info >= Level::Info);
328                 assert!(Level::Debug > Level::Trace);
329                 assert!(Level::Debug >= Level::Trace);
330                 assert!(Level::Debug >= Level::Debug);
331                 assert!(Level::Trace > Level::Gossip);
332                 assert!(Level::Trace >= Level::Gossip);
333                 assert!(Level::Trace >= Level::Trace);
334                 assert!(Level::Gossip >= Level::Gossip);
335
336                 assert!(Level::Error <= Level::Error);
337                 assert!(Level::Warn < Level::Error);
338                 assert!(Level::Warn <= Level::Error);
339                 assert!(Level::Warn <= Level::Warn);
340                 assert!(Level::Info < Level::Warn);
341                 assert!(Level::Info <= Level::Warn);
342                 assert!(Level::Info <= Level::Info);
343                 assert!(Level::Debug < Level::Info);
344                 assert!(Level::Debug <= Level::Info);
345                 assert!(Level::Debug <= Level::Debug);
346                 assert!(Level::Trace < Level::Debug);
347                 assert!(Level::Trace <= Level::Debug);
348                 assert!(Level::Trace <= Level::Trace);
349                 assert!(Level::Gossip < Level::Trace);
350                 assert!(Level::Gossip <= Level::Trace);
351                 assert!(Level::Gossip <= Level::Gossip);
352         }
353 }