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