Bump workspace to rust edition 2018
[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         /// (C-not exported) as fmt can't be used in C
120         #[inline]
121         pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'static str, file: &'static str, line: u32) -> Record<'a> {
122                 Record {
123                         level,
124                         #[cfg(not(c_bindings))]
125                         args,
126                         #[cfg(c_bindings)]
127                         args: format!("{}", args),
128                         module_path,
129                         file,
130                         line,
131                         #[cfg(c_bindings)]
132                         _phantom: core::marker::PhantomData,
133                 }
134         }
135 }
136
137 /// A trait encapsulating the operations required of a logger
138 pub trait Logger {
139         /// Logs the `Record`
140         fn log(&self, record: &Record);
141 }
142
143 /// Wrapper for logging a [`PublicKey`] in hex format.
144 /// (C-not exported) as fmt can't be used in C
145 #[doc(hidden)]
146 pub struct DebugPubKey<'a>(pub &'a PublicKey);
147 impl<'a> core::fmt::Display for DebugPubKey<'a> {
148         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
149                 for i in self.0.serialize().iter() {
150                         write!(f, "{:02x}", i)?;
151                 }
152                 Ok(())
153         }
154 }
155
156 /// Wrapper for logging byte slices in hex format.
157 /// (C-not exported) as fmt can't be used in C
158 #[doc(hidden)]
159 pub struct DebugBytes<'a>(pub &'a [u8]);
160 impl<'a> core::fmt::Display for DebugBytes<'a> {
161         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
162                 for i in self.0 {
163                         write!(f, "{:02x}", i)?;
164                 }
165                 Ok(())
166         }
167 }
168
169 #[cfg(test)]
170 mod tests {
171         use crate::util::logger::{Logger, Level};
172         use crate::util::test_utils::TestLogger;
173         use crate::sync::Arc;
174
175         #[test]
176         fn test_level_show() {
177                 assert_eq!("INFO", Level::Info.to_string());
178                 assert_eq!("ERROR", Level::Error.to_string());
179                 assert_ne!("WARN", Level::Error.to_string());
180         }
181
182         struct WrapperLog {
183                 logger: Arc<Logger>
184         }
185
186         impl WrapperLog {
187                 fn new(logger: Arc<Logger>) -> WrapperLog {
188                         WrapperLog {
189                                 logger,
190                         }
191                 }
192
193                 fn call_macros(&self) {
194                         log_error!(self.logger, "This is an error");
195                         log_warn!(self.logger, "This is a warning");
196                         log_info!(self.logger, "This is an info");
197                         log_debug!(self.logger, "This is a debug");
198                         log_trace!(self.logger, "This is a trace");
199                         log_gossip!(self.logger, "This is a gossip");
200                 }
201         }
202
203         #[test]
204         fn test_logging_macros() {
205                 let mut logger = TestLogger::new();
206                 logger.enable(Level::Gossip);
207                 let logger : Arc<Logger> = Arc::new(logger);
208                 let wrapper = WrapperLog::new(Arc::clone(&logger));
209                 wrapper.call_macros();
210         }
211
212         #[test]
213         fn test_log_ordering() {
214                 assert!(Level::Error > Level::Warn);
215                 assert!(Level::Error >= Level::Warn);
216                 assert!(Level::Error >= Level::Error);
217                 assert!(Level::Warn > Level::Info);
218                 assert!(Level::Warn >= Level::Info);
219                 assert!(Level::Warn >= Level::Warn);
220                 assert!(Level::Info > Level::Debug);
221                 assert!(Level::Info >= Level::Debug);
222                 assert!(Level::Info >= Level::Info);
223                 assert!(Level::Debug > Level::Trace);
224                 assert!(Level::Debug >= Level::Trace);
225                 assert!(Level::Debug >= Level::Debug);
226                 assert!(Level::Trace > Level::Gossip);
227                 assert!(Level::Trace >= Level::Gossip);
228                 assert!(Level::Trace >= Level::Trace);
229                 assert!(Level::Gossip >= Level::Gossip);
230
231                 assert!(Level::Error <= Level::Error);
232                 assert!(Level::Warn < Level::Error);
233                 assert!(Level::Warn <= Level::Error);
234                 assert!(Level::Warn <= Level::Warn);
235                 assert!(Level::Info < Level::Warn);
236                 assert!(Level::Info <= Level::Warn);
237                 assert!(Level::Info <= Level::Info);
238                 assert!(Level::Debug < Level::Info);
239                 assert!(Level::Debug <= Level::Info);
240                 assert!(Level::Debug <= Level::Debug);
241                 assert!(Level::Trace < Level::Debug);
242                 assert!(Level::Trace <= Level::Debug);
243                 assert!(Level::Trace <= Level::Trace);
244                 assert!(Level::Gossip < Level::Trace);
245                 assert!(Level::Gossip <= Level::Trace);
246                 assert!(Level::Gossip <= Level::Gossip);
247         }
248 }