Replacing (C-not exported) in the docs
[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 #[cfg(test)]
173 mod tests {
174         use crate::util::logger::{Logger, Level};
175         use crate::util::test_utils::TestLogger;
176         use crate::sync::Arc;
177
178         #[test]
179         fn test_level_show() {
180                 assert_eq!("INFO", Level::Info.to_string());
181                 assert_eq!("ERROR", Level::Error.to_string());
182                 assert_ne!("WARN", Level::Error.to_string());
183         }
184
185         struct WrapperLog {
186                 logger: Arc<Logger>
187         }
188
189         impl WrapperLog {
190                 fn new(logger: Arc<Logger>) -> WrapperLog {
191                         WrapperLog {
192                                 logger,
193                         }
194                 }
195
196                 fn call_macros(&self) {
197                         log_error!(self.logger, "This is an error");
198                         log_warn!(self.logger, "This is a warning");
199                         log_info!(self.logger, "This is an info");
200                         log_debug!(self.logger, "This is a debug");
201                         log_trace!(self.logger, "This is a trace");
202                         log_gossip!(self.logger, "This is a gossip");
203                 }
204         }
205
206         #[test]
207         fn test_logging_macros() {
208                 let mut logger = TestLogger::new();
209                 logger.enable(Level::Gossip);
210                 let logger : Arc<Logger> = Arc::new(logger);
211                 let wrapper = WrapperLog::new(Arc::clone(&logger));
212                 wrapper.call_macros();
213         }
214
215         #[test]
216         fn test_log_ordering() {
217                 assert!(Level::Error > Level::Warn);
218                 assert!(Level::Error >= Level::Warn);
219                 assert!(Level::Error >= Level::Error);
220                 assert!(Level::Warn > Level::Info);
221                 assert!(Level::Warn >= Level::Info);
222                 assert!(Level::Warn >= Level::Warn);
223                 assert!(Level::Info > Level::Debug);
224                 assert!(Level::Info >= Level::Debug);
225                 assert!(Level::Info >= Level::Info);
226                 assert!(Level::Debug > Level::Trace);
227                 assert!(Level::Debug >= Level::Trace);
228                 assert!(Level::Debug >= Level::Debug);
229                 assert!(Level::Trace > Level::Gossip);
230                 assert!(Level::Trace >= Level::Gossip);
231                 assert!(Level::Trace >= Level::Trace);
232                 assert!(Level::Gossip >= Level::Gossip);
233
234                 assert!(Level::Error <= Level::Error);
235                 assert!(Level::Warn < Level::Error);
236                 assert!(Level::Warn <= Level::Error);
237                 assert!(Level::Warn <= Level::Warn);
238                 assert!(Level::Info < Level::Warn);
239                 assert!(Level::Info <= Level::Warn);
240                 assert!(Level::Info <= Level::Info);
241                 assert!(Level::Debug < Level::Info);
242                 assert!(Level::Debug <= Level::Info);
243                 assert!(Level::Debug <= Level::Debug);
244                 assert!(Level::Trace < Level::Debug);
245                 assert!(Level::Trace <= Level::Debug);
246                 assert!(Level::Trace <= Level::Trace);
247                 assert!(Level::Gossip < Level::Trace);
248                 assert!(Level::Gossip <= Level::Trace);
249                 assert!(Level::Gossip <= Level::Gossip);
250         }
251 }