98037aac298280a5b418b9c84bb94b948ae3bc30
[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 core::cmp;
18 use core::fmt;
19
20 static LOG_LEVEL_NAMES: [&'static str; 5] = ["TRACE", "DEBUG", "INFO", "WARN", "ERROR"];
21
22 /// An enum representing the available verbosity levels of the logger.
23 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
24 pub enum Level {
25         /// Designates very low priority, often extremely verbose, information
26         Trace,
27         /// Designates lower priority information
28         Debug,
29         /// Designates useful information
30         Info,
31         /// Designates hazardous situations
32         Warn,
33         /// Designates very serious errors
34         Error,
35 }
36
37 impl PartialOrd for Level {
38         #[inline]
39         fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
40                 Some(self.cmp(other))
41         }
42
43         #[inline]
44         fn lt(&self, other: &Level) -> bool {
45                 (*self as usize) < *other as usize
46         }
47
48         #[inline]
49         fn le(&self, other: &Level) -> bool {
50                 *self as usize <= *other as usize
51         }
52
53         #[inline]
54         fn gt(&self, other: &Level) -> bool {
55                 *self as usize > *other as usize
56         }
57
58         #[inline]
59         fn ge(&self, other: &Level) -> bool {
60                 *self as usize >= *other as usize
61         }
62 }
63
64 impl Ord for Level {
65         #[inline]
66         fn cmp(&self, other: &Level) -> cmp::Ordering {
67                 (*self as usize).cmp(&(*other as usize))
68         }
69 }
70
71 impl fmt::Display for Level {
72         fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
73                 fmt.pad(LOG_LEVEL_NAMES[*self as usize])
74         }
75 }
76
77 impl Level {
78         /// Returns the most verbose logging level.
79         #[inline]
80         pub fn max() -> Level {
81                 Level::Trace
82         }
83 }
84
85 /// A Record, unit of logging output with Metadata to enable filtering
86 /// Module_path, file, line to inform on log's source
87 /// (C-not exported) - we convert to a const char* instead
88 #[derive(Clone,Debug)]
89 pub struct Record<'a> {
90         /// The verbosity level of the message.
91         pub level: Level,
92         /// The message body.
93         pub args: fmt::Arguments<'a>,
94         /// The module path of the message.
95         pub module_path: &'a str,
96         /// The source file containing the message.
97         pub file: &'a str,
98         /// The line containing the message.
99         pub line: u32,
100 }
101
102 impl<'a> Record<'a> {
103         /// Returns a new Record.
104         /// (C-not exported) as fmt can't be used in C
105         #[inline]
106         pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'a str, file: &'a str, line: u32) -> Record<'a> {
107                 Record {
108                         level,
109                         args,
110                         module_path,
111                         file,
112                         line
113                 }
114         }
115 }
116
117 /// A trait encapsulating the operations required of a logger
118 pub trait Logger {
119         /// Logs the `Record`
120         fn log(&self, record: &Record);
121 }
122
123 #[cfg(test)]
124 mod tests {
125         use util::logger::{Logger, Level};
126         use util::test_utils::TestLogger;
127         use std::sync::Arc;
128
129         #[test]
130         fn test_level_show() {
131                 assert_eq!("INFO", Level::Info.to_string());
132                 assert_eq!("ERROR", Level::Error.to_string());
133                 assert_ne!("WARN", Level::Error.to_string());
134         }
135
136         struct WrapperLog {
137                 logger: Arc<Logger>
138         }
139
140         impl WrapperLog {
141                 fn new(logger: Arc<Logger>) -> WrapperLog {
142                         WrapperLog {
143                                 logger,
144                         }
145                 }
146
147                 fn call_macros(&self) {
148                         log_error!(self.logger, "This is an error");
149                         log_warn!(self.logger, "This is a warning");
150                         log_info!(self.logger, "This is an info");
151                         log_debug!(self.logger, "This is a debug");
152                         log_trace!(self.logger, "This is a trace");
153                 }
154         }
155
156         #[test]
157         fn test_logging_macros() {
158                 let mut logger = TestLogger::new();
159                 logger.enable(Level::Trace);
160                 let logger : Arc<Logger> = Arc::new(logger);
161                 let wrapper = WrapperLog::new(Arc::clone(&logger));
162                 wrapper.call_macros();
163         }
164
165         #[test]
166         fn test_log_ordering() {
167                 assert!(Level::Error > Level::Warn);
168                 assert!(Level::Error >= Level::Warn);
169                 assert!(Level::Error >= Level::Error);
170                 assert!(Level::Warn > Level::Info);
171                 assert!(Level::Warn >= Level::Info);
172                 assert!(Level::Warn >= Level::Warn);
173                 assert!(Level::Info > Level::Debug);
174                 assert!(Level::Info >= Level::Debug);
175                 assert!(Level::Info >= Level::Info);
176                 assert!(Level::Debug > Level::Trace);
177                 assert!(Level::Debug >= Level::Trace);
178                 assert!(Level::Debug >= Level::Debug);
179                 assert!(Level::Trace >= Level::Trace);
180
181                 assert!(Level::Error <= Level::Error);
182                 assert!(Level::Warn < Level::Error);
183                 assert!(Level::Warn <= Level::Error);
184                 assert!(Level::Warn <= Level::Warn);
185                 assert!(Level::Info < Level::Warn);
186                 assert!(Level::Info <= Level::Warn);
187                 assert!(Level::Info <= Level::Info);
188                 assert!(Level::Debug < Level::Info);
189                 assert!(Level::Debug <= Level::Info);
190                 assert!(Level::Debug <= Level::Debug);
191                 assert!(Level::Trace < Level::Debug);
192                 assert!(Level::Trace <= Level::Debug);
193                 assert!(Level::Trace <= Level::Trace);
194         }
195 }