1 // Pruned copy of crate rust log, without global logger
2 // https://github.com/rust-lang-nursery/log #7a60286
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
10 //! Log traits live here, which are called throughout the library to provide useful information for
11 //! debugging purposes.
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.
17 use bitcoin::secp256k1::PublicKey;
22 use crate::ln::ChannelId;
24 use crate::prelude::*; // Needed for String
26 static LOG_LEVEL_NAMES: [&'static str; 6] = ["GOSSIP", "TRACE", "DEBUG", "INFO", "WARN", "ERROR"];
28 /// An enum representing the available verbosity levels of the logger.
29 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
31 /// Designates extremely verbose information, including gossip-induced messages
33 /// Designates very low priority, often extremely verbose, information
35 /// Designates lower priority information
37 /// Designates useful information
39 /// Designates hazardous situations
41 /// Designates very serious errors
45 impl PartialOrd for Level {
47 fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
52 fn lt(&self, other: &Level) -> bool {
53 (*self as usize) < *other as usize
57 fn le(&self, other: &Level) -> bool {
58 *self as usize <= *other as usize
62 fn gt(&self, other: &Level) -> bool {
63 *self as usize > *other as usize
67 fn ge(&self, other: &Level) -> bool {
68 *self as usize >= *other as usize
74 fn cmp(&self, other: &Level) -> cmp::Ordering {
75 (*self as usize).cmp(&(*other as usize))
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])
86 /// Returns the most verbose logging level.
88 pub fn max() -> Level {
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.
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>,
108 /// The message body.
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.
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 ()>,
123 impl<'a> Record<'a> {
124 /// Returns a new Record.
126 /// This is not exported to bindings users as fmt can't be used in C
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
136 #[cfg(not(c_bindings))]
139 args: format!("{}", args),
144 _phantom: core::marker::PhantomData,
149 /// A trait encapsulating the operations required of a logger.
151 /// Logs the [`Record`].
152 fn log(&self, record: Record);
155 /// Wrapper for logging a [`PublicKey`] in hex format.
157 /// This is not exported to bindings users as fmt can't be used in C
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)?;
169 /// Wrapper for logging byte slices in hex format.
171 /// This is not exported to bindings users as fmt can't be used in C
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> {
177 write!(f, "{:02x}", i)?;
183 /// Wrapper for logging `Iterator`s.
185 /// This is not exported to bindings users as fmt can't be used in C
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> {
191 let mut iter = self.0.clone();
192 if let Some(item) = iter.next() {
193 write!(f, "{}", item)?;
195 while let Some(item) = iter.next() {
196 write!(f, ", {}", item)?;
205 use crate::util::logger::{Logger, Level};
206 use crate::util::test_utils::TestLogger;
207 use crate::sync::Arc;
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());
221 fn new(logger: Arc<Logger>) -> WrapperLog {
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");
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();
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);
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);