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;
23 use crate::ln::ChannelId;
25 use crate::prelude::*; // Needed for String
27 static LOG_LEVEL_NAMES: [&'static str; 6] = ["GOSSIP", "TRACE", "DEBUG", "INFO", "WARN", "ERROR"];
29 /// An enum representing the available verbosity levels of the logger.
30 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
32 /// Designates extremely verbose information, including gossip-induced messages
34 /// Designates very low priority, often extremely verbose, information
36 /// Designates lower priority information
38 /// Designates useful information
40 /// Designates hazardous situations
42 /// Designates very serious errors
46 impl PartialOrd for Level {
48 fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
53 fn lt(&self, other: &Level) -> bool {
54 (*self as usize) < *other as usize
58 fn le(&self, other: &Level) -> bool {
59 *self as usize <= *other as usize
63 fn gt(&self, other: &Level) -> bool {
64 *self as usize > *other as usize
68 fn ge(&self, other: &Level) -> bool {
69 *self as usize >= *other as usize
75 fn cmp(&self, other: &Level) -> cmp::Ordering {
76 (*self as usize).cmp(&(*other as usize))
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])
87 /// Returns the most verbose logging level.
89 pub fn max() -> Level {
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.
100 /// The node id of the peer pertaining to the logged record.
102 /// Note that in some cases a [`Self::channel_id`] may be filled in but this may still be
103 /// `None`, depending on if the peer information is readily available in LDK when the log is
105 pub peer_id: Option<PublicKey>,
106 /// The channel id of the channel pertaining to the logged record. May be a temporary id before
107 /// the channel has been funded.
108 pub channel_id: Option<ChannelId>,
109 #[cfg(not(c_bindings))]
110 /// The message body.
111 pub args: fmt::Arguments<'a>,
113 /// The message body.
115 /// The module path of the message.
116 pub module_path: &'static str,
117 /// The source file containing the message.
118 pub file: &'static str,
119 /// The line containing the message.
123 /// We don't actually use the lifetime parameter in C bindings (as there is no good way to
124 /// communicate a lifetime to a C, or worse, Java user).
125 _phantom: core::marker::PhantomData<&'a ()>,
128 impl<'a> Record<'a> {
129 /// Returns a new Record.
131 /// This is not exported to bindings users as fmt can't be used in C
134 level: Level, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>,
135 args: fmt::Arguments<'a>, module_path: &'static str, file: &'static str, line: u32
141 #[cfg(not(c_bindings))]
144 args: format!("{}", args),
149 _phantom: core::marker::PhantomData,
154 /// A trait encapsulating the operations required of a logger.
156 /// Logs the [`Record`].
157 fn log(&self, record: Record);
160 /// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`].
161 pub struct WithContext<'a, L: Deref> where L::Target: Logger {
162 /// The logger to delegate to after adding context to the record.
164 /// The node id of the peer pertaining to the logged record.
165 peer_id: Option<PublicKey>,
166 /// The channel id of the channel pertaining to the logged record.
167 channel_id: Option<ChannelId>,
170 impl<'a, L: Deref> Logger for WithContext<'a, L> where L::Target: Logger {
171 fn log(&self, mut record: Record) {
172 if self.peer_id.is_some() {
173 record.peer_id = self.peer_id
175 if self.channel_id.is_some() {
176 record.channel_id = self.channel_id;
178 self.logger.log(record)
182 impl<'a, L: Deref> WithContext<'a, L> where L::Target: Logger {
183 /// Wraps the given logger, providing additional context to any logged records.
184 pub fn from(logger: &'a L, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>) -> Self {
193 /// Wrapper for logging a [`PublicKey`] in hex format.
195 /// This is not exported to bindings users as fmt can't be used in C
197 pub struct DebugPubKey<'a>(pub &'a PublicKey);
198 impl<'a> core::fmt::Display for DebugPubKey<'a> {
199 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
200 for i in self.0.serialize().iter() {
201 write!(f, "{:02x}", i)?;
207 /// Wrapper for logging byte slices in hex format.
209 /// This is not exported to bindings users as fmt can't be used in C
211 pub struct DebugBytes<'a>(pub &'a [u8]);
212 impl<'a> core::fmt::Display for DebugBytes<'a> {
213 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
215 write!(f, "{:02x}", i)?;
221 /// Wrapper for logging `Iterator`s.
223 /// This is not exported to bindings users as fmt can't be used in C
225 pub struct DebugIter<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone>(pub I);
226 impl<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone> fmt::Display for DebugIter<T, I> {
227 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
229 let mut iter = self.0.clone();
230 if let Some(item) = iter.next() {
231 write!(f, "{}", item)?;
233 while let Some(item) = iter.next() {
234 write!(f, ", {}", item)?;
243 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
244 use crate::ln::ChannelId;
245 use crate::util::logger::{Logger, Level, WithContext};
246 use crate::util::test_utils::TestLogger;
247 use crate::sync::Arc;
250 fn test_level_show() {
251 assert_eq!("INFO", Level::Info.to_string());
252 assert_eq!("ERROR", Level::Error.to_string());
253 assert_ne!("WARN", Level::Error.to_string());
257 logger: Arc<dyn Logger>
261 fn new(logger: Arc<dyn Logger>) -> WrapperLog {
267 fn call_macros(&self) {
268 log_error!(self.logger, "This is an error");
269 log_warn!(self.logger, "This is a warning");
270 log_info!(self.logger, "This is an info");
271 log_debug!(self.logger, "This is a debug");
272 log_trace!(self.logger, "This is a trace");
273 log_gossip!(self.logger, "This is a gossip");
278 fn test_logging_macros() {
279 let mut logger = TestLogger::new();
280 logger.enable(Level::Gossip);
281 let logger : Arc<dyn Logger> = Arc::new(logger);
282 let wrapper = WrapperLog::new(Arc::clone(&logger));
283 wrapper.call_macros();
287 fn test_logging_with_context() {
288 let logger = &TestLogger::new();
289 let secp_ctx = Secp256k1::new();
290 let pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
291 let context_logger = WithContext::from(&logger, Some(pk), Some(ChannelId([0; 32])));
292 log_error!(context_logger, "This is an error");
293 log_warn!(context_logger, "This is an error");
294 log_debug!(context_logger, "This is an error");
295 log_trace!(context_logger, "This is an error");
296 log_gossip!(context_logger, "This is an error");
297 log_info!(context_logger, "This is an error");
298 logger.assert_log_context_contains(
299 "lightning::util::logger::tests", Some(pk), Some(ChannelId([0;32])), 6
304 fn test_logging_with_multiple_wrapped_context() {
305 let logger = &TestLogger::new();
306 let secp_ctx = Secp256k1::new();
307 let pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
308 let context_logger = &WithContext::from(&logger, None, Some(ChannelId([0; 32])));
309 let full_context_logger = WithContext::from(&context_logger, Some(pk), None);
310 log_error!(full_context_logger, "This is an error");
311 log_warn!(full_context_logger, "This is an error");
312 log_debug!(full_context_logger, "This is an error");
313 log_trace!(full_context_logger, "This is an error");
314 log_gossip!(full_context_logger, "This is an error");
315 log_info!(full_context_logger, "This is an error");
316 logger.assert_log_context_contains(
317 "lightning::util::logger::tests", Some(pk), Some(ChannelId([0;32])), 6
322 fn test_log_ordering() {
323 assert!(Level::Error > Level::Warn);
324 assert!(Level::Error >= Level::Warn);
325 assert!(Level::Error >= Level::Error);
326 assert!(Level::Warn > Level::Info);
327 assert!(Level::Warn >= Level::Info);
328 assert!(Level::Warn >= Level::Warn);
329 assert!(Level::Info > Level::Debug);
330 assert!(Level::Info >= Level::Debug);
331 assert!(Level::Info >= Level::Info);
332 assert!(Level::Debug > Level::Trace);
333 assert!(Level::Debug >= Level::Trace);
334 assert!(Level::Debug >= Level::Debug);
335 assert!(Level::Trace > Level::Gossip);
336 assert!(Level::Trace >= Level::Gossip);
337 assert!(Level::Trace >= Level::Trace);
338 assert!(Level::Gossip >= Level::Gossip);
340 assert!(Level::Error <= Level::Error);
341 assert!(Level::Warn < Level::Error);
342 assert!(Level::Warn <= Level::Error);
343 assert!(Level::Warn <= Level::Warn);
344 assert!(Level::Info < Level::Warn);
345 assert!(Level::Info <= Level::Warn);
346 assert!(Level::Info <= Level::Info);
347 assert!(Level::Debug < Level::Info);
348 assert!(Level::Debug <= Level::Info);
349 assert!(Level::Debug <= Level::Debug);
350 assert!(Level::Trace < Level::Debug);
351 assert!(Level::Trace <= Level::Debug);
352 assert!(Level::Trace <= Level::Trace);
353 assert!(Level::Gossip < Level::Trace);
354 assert!(Level::Gossip <= Level::Trace);
355 assert!(Level::Gossip <= Level::Gossip);