Logging interface
[rust-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 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 /// There is currently 2 ways to filter log messages. First one, by using compilation flag, e.g "max_level_off".
11 /// The second one, client-side by implementing check against Record Level field, e.g TestLogger in test_utils.
12 /// Each module may have its own Logger or share one.
13
14 use std::cmp;
15 use std::fmt;
16
17 static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
18
19 /// An enum representing the available verbosity levels of the logger.
20 #[derive(Copy, Clone, Eq, Debug, Hash)]
21 pub enum Level {
22         ///Designates logger being silent
23         Off,
24         /// Designates very serious errors
25         Error,
26         /// Designates hazardous situations
27         Warn,
28         /// Designates useful information
29         Info,
30         /// Designates lower priority information
31         Debug,
32         /// Designates very low priority, often extremely verbose, information
33         Trace,
34 }
35
36 impl PartialEq for Level {
37         #[inline]
38         fn eq(&self, other: &Level) -> bool {
39                 *self as usize == *other as usize
40         }
41 }
42
43 impl PartialOrd for Level {
44         #[inline]
45         fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
46                 Some(self.cmp(other))
47         }
48
49         #[inline]
50         fn lt(&self, other: &Level) -> bool {
51                 (*self as usize) < *other as usize
52         }
53
54         #[inline]
55         fn le(&self, other: &Level) -> bool {
56                 *self as usize <= *other as usize
57         }
58
59         #[inline]
60         fn gt(&self, other: &Level) -> bool {
61                 *self as usize > *other as usize
62         }
63
64         #[inline]
65         fn ge(&self, other: &Level) -> bool {
66                 *self as usize >= *other as usize
67         }
68 }
69
70 impl Ord for Level {
71         #[inline]
72         fn cmp(&self, other: &Level) -> cmp::Ordering {
73                 (*self as usize).cmp(&(*other as usize))
74         }
75 }
76
77 impl fmt::Display for Level {
78         fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
79                 fmt.pad(LOG_LEVEL_NAMES[*self as usize])
80         }
81 }
82
83 impl Level {
84         /// Returns the most verbose logging level.
85         #[inline]
86         pub fn max() -> Level {
87                 Level::Trace
88         }
89 }
90
91 /// A Record, unit of logging output with Metadata to enable filtering
92 /// Module_path, file, line to inform on log's source
93 #[derive(Clone,Debug)]
94 pub struct Record<'a> {
95         /// The verbosity level of the message.
96         pub level: Level,
97         /// The message body.
98         pub args: fmt::Arguments<'a>,
99         /// The module path of the message.
100         pub module_path: &'a str,
101         /// The source file containing the message.
102         pub file: &'a str,
103         /// The line containing the message.
104         pub line: u32,
105 }
106
107 impl<'a> Record<'a> {
108         /// Returns a new Record.
109         #[inline]
110         pub fn new(level: Level, args: fmt::Arguments<'a>, module_path: &'a str, file: &'a str, line: u32) -> Record<'a> {
111                 Record {
112                         level,
113                         args,
114                         module_path,
115                         file,
116                         line
117                 }
118         }
119 }
120
121 /// A trait encapsulating the operations required of a logger
122 pub trait Logger: Sync + Send {
123         /// Logs the `Record`
124         fn log(&self, record: &Record);
125 }
126
127 #[cfg(test)]
128 mod tests {
129         use util::logger::{Logger, Level, Record};
130         use util::test_utils::TestLogger;
131         use std::sync::{Arc};
132
133         #[test]
134         fn test_level_show() {
135                 assert_eq!("INFO", Level::Info.to_string());
136                 assert_eq!("ERROR", Level::Error.to_string());
137                 assert_ne!("WARN", Level::Error.to_string());
138         }
139
140         struct WrapperLog {
141                 logger: Arc<Logger>
142         }
143
144         impl WrapperLog {
145                 fn new(logger: Arc<Logger>) -> WrapperLog {
146                         WrapperLog {
147                                 logger,
148                         }
149                 }
150
151                 fn call_macros(&self) {
152                         log_error!(self, "This is an error");
153                         log_warn!(self, "This is a warning");
154                         log_info!(self, "This is an info");
155                         log_debug!(self, "This is a debug");
156                         log_trace!(self, "This is a trace");
157                 }
158         }
159
160         #[test]
161         fn test_logging_macros() {
162                 let mut logger = TestLogger::new();
163                 logger.enable(Level::Trace);
164                 let logger : Arc<Logger> = Arc::new(logger);
165                 let wrapper = WrapperLog::new(Arc::clone(&logger));
166                 wrapper.call_macros();
167         }
168 }