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