]> git.lizzy.rs Git - rust.git/blob - src/liblog/lib.rs
Convert most code to new inner attribute syntax.
[rust.git] / src / liblog / lib.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12
13 Utilities for program-wide and customizable logging
14
15 ## Example
16
17 ```
18 #[feature(phase)];
19 #[phase(syntax, link)] extern crate log;
20
21 fn main() {
22     debug!("this is a debug {}", "message");
23     error!("this is printed by default");
24
25     if log_enabled!(log::INFO) {
26         let x = 3 * 4; // expensive computation
27         info!("the answer was: {}", x);
28     }
29 }
30 ```
31
32 ## Logging Macros
33
34 There are five macros that the logging subsystem uses:
35
36 * `log!(level, ...)` - the generic logging macro, takes a level as a u32 and any
37                        related `format!` arguments
38 * `debug!(...)` - a macro hard-wired to the log level of `DEBUG`
39 * `info!(...)` - a macro hard-wired to the log level of `INFO`
40 * `warn!(...)` - a macro hard-wired to the log level of `WARN`
41 * `error!(...)` - a macro hard-wired to the log level of `ERROR`
42
43 All of these macros use std::the same style of syntax as the `format!` syntax
44 extension. Details about the syntax can be found in the documentation of
45 `std::fmt` along with the Rust tutorial/manual.
46
47 If you want to check at runtime if a given logging level is enabled (e.g. if the
48 information you would want to log is expensive to produce), you can use std::the
49 following macro:
50
51 * `log_enabled!(level)` - returns true if logging of the given level is enabled
52
53 ## Enabling logging
54
55 Log levels are controlled on a per-module basis, and by default all logging is
56 disabled except for `error!` (a log level of 1). Logging is controlled via the
57 `RUST_LOG` environment variable. The value of this environment variable is a
58 comma-separated list of logging directives. A logging directive is of the form:
59
60 ```notrust
61 path::to::module=log_level
62 ```
63
64 The path to the module is rooted in the name of the crate it was compiled for,
65 so if your program is contained in a file `hello.rs`, for example, to turn on
66 logging for this file you would use std::a value of `RUST_LOG=hello`.
67 Furthermore, this path is a prefix-search, so all modules nested in the
68 specified module will also have logging enabled.
69
70 The actual `log_level` is optional to specify. If omitted, all logging will be
71 enabled. If specified, the it must be either a numeric in the range of 1-255, or
72 it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric
73 is specified, then all logging less than or equal to that numeral is enabled.
74 For example, if logging level 3 is active, error, warn, and info logs will be
75 printed, but debug will be omitted.
76
77 As the log level for a module is optional, the module to enable logging for is
78 also optional. If only a `log_level` is provided, then the global log level for
79 all modules is set to this value.
80
81 Some examples of valid values of `RUST_LOG` are:
82
83 ```notrust
84 hello                // turns on all logging for the 'hello' module
85 info                 // turns on all info logging
86 hello=debug          // turns on debug logging for 'hello'
87 hello=3              // turns on info logging for 'hello'
88 hello,std::option    // turns on hello, and std's option logging
89 error,hello=warn     // turn on global error logging and also warn for hello
90 ```
91
92 ## Performance and Side Effects
93
94 Each of these macros will expand to code similar to:
95
96 ```rust,ignore
97 if log_level <= my_module_log_level() {
98     ::log::log(log_level, format!(...));
99 }
100 ```
101
102 What this means is that each of these macros are very cheap at runtime if
103 they're turned off (just a load and an integer comparison). This also means that
104 if logging is disabled, none of the components of the log will be executed.
105
106 */
107
108 #![crate_id = "log#0.10-pre"]
109 #![license = "MIT/ASL2"]
110 #![crate_type = "rlib"]
111 #![crate_type = "dylib"]
112 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
113        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
114        html_root_url = "http://static.rust-lang.org/doc/master")]
115
116 #![feature(macro_rules)]
117 #![deny(missing_doc, deprecated_owned_vector)]
118
119 extern crate sync;
120
121 use std::cast;
122 use std::fmt;
123 use std::io::LineBufferedWriter;
124 use std::io;
125 use std::local_data;
126 use std::os;
127 use std::rt;
128 use std::slice;
129
130 use sync::one::{Once, ONCE_INIT};
131
132 pub mod macros;
133 mod directive;
134
135 /// Maximum logging level of a module that can be specified. Common logging
136 /// levels are found in the DEBUG/INFO/WARN/ERROR constants.
137 pub static MAX_LOG_LEVEL: u32 = 255;
138
139 /// The default logging level of a crate if no other is specified.
140 static DEFAULT_LOG_LEVEL: u32 = 1;
141
142 /// An unsafe constant that is the maximum logging level of any module
143 /// specified. This is the first line of defense to determining whether a
144 /// logging statement should be run.
145 static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
146
147 static mut DIRECTIVES: *Vec<directive::LogDirective> =
148     0 as *Vec<directive::LogDirective>;
149
150 /// Debug log level
151 pub static DEBUG: u32 = 4;
152 /// Info log level
153 pub static INFO: u32 = 3;
154 /// Warn log level
155 pub static WARN: u32 = 2;
156 /// Error log level
157 pub static ERROR: u32 = 1;
158
159 local_data_key!(local_logger: ~Logger:Send)
160
161 /// A trait used to represent an interface to a task-local logger. Each task
162 /// can have its own custom logger which can respond to logging messages
163 /// however it likes.
164 pub trait Logger {
165     /// Logs a single message described by the `args` structure. The level is
166     /// provided in case you want to do things like color the message, etc.
167     fn log(&mut self, level: u32, args: &fmt::Arguments);
168 }
169
170 struct DefaultLogger {
171     handle: LineBufferedWriter<io::stdio::StdWriter>,
172 }
173
174 impl Logger for DefaultLogger {
175     // by default, just ignore the level
176     fn log(&mut self, _level: u32, args: &fmt::Arguments) {
177         match fmt::writeln(&mut self.handle, args) {
178             Err(e) => fail!("failed to log: {}", e),
179             Ok(()) => {}
180         }
181     }
182 }
183
184 impl Drop for DefaultLogger {
185     fn drop(&mut self) {
186         // FIXME(#12628): is failure the right thing to do?
187         match self.handle.flush() {
188             Err(e) => fail!("failed to flush a logger: {}", e),
189             Ok(()) => {}
190         }
191     }
192 }
193
194 /// This function is called directly by the compiler when using the logging
195 /// macros. This function does not take into account whether the log level
196 /// specified is active or not, it will always log something if this method is
197 /// called.
198 ///
199 /// It is not recommended to call this function directly, rather it should be
200 /// invoked through the logging family of macros.
201 pub fn log(level: u32, args: &fmt::Arguments) {
202     // Completely remove the local logger from TLS in case anyone attempts to
203     // frob the slot while we're doing the logging. This will destroy any logger
204     // set during logging.
205     let mut logger = local_data::pop(local_logger).unwrap_or_else(|| {
206         ~DefaultLogger { handle: io::stderr() } as ~Logger:Send
207     });
208     logger.log(level, args);
209     local_data::set(local_logger, logger);
210 }
211
212 /// Getter for the global log level. This is a function so that it can be called
213 /// safely
214 #[doc(hidden)]
215 #[inline(always)]
216 pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
217
218 /// Replaces the task-local logger with the specified logger, returning the old
219 /// logger.
220 pub fn set_logger(logger: ~Logger:Send) -> Option<~Logger:Send> {
221     let prev = local_data::pop(local_logger);
222     local_data::set(local_logger, logger);
223     return prev;
224 }
225
226 /// Tests whether a given module's name is enabled for a particular level of
227 /// logging. This is the second layer of defense about determining whether a
228 /// module's log statement should be emitted or not.
229 #[doc(hidden)]
230 pub fn mod_enabled(level: u32, module: &str) -> bool {
231     static mut INIT: Once = ONCE_INIT;
232     unsafe { INIT.doit(init); }
233
234     // It's possible for many threads are in this function, only one of them
235     // will peform the global initialization, but all of them will need to check
236     // again to whether they should really be here or not. Hence, despite this
237     // check being expanded manually in the logging macro, this function checks
238     // the log level again.
239     if level > unsafe { LOG_LEVEL } { return false }
240
241     // This assertion should never get tripped unless we're in an at_exit
242     // handler after logging has been torn down and a logging attempt was made.
243     assert!(unsafe { !DIRECTIVES.is_null() });
244
245     enabled(level, module, unsafe { (*DIRECTIVES).iter() })
246 }
247
248 fn enabled(level: u32, module: &str,
249            iter: slice::Items<directive::LogDirective>) -> bool {
250     // Search for the longest match, the vector is assumed to be pre-sorted.
251     for directive in iter.rev() {
252         match directive.name {
253             Some(ref name) if !module.starts_with(*name) => {},
254             Some(..) | None => {
255                 return level <= directive.level
256             }
257         }
258     }
259     level <= DEFAULT_LOG_LEVEL
260 }
261
262 /// Initialize logging for the current process.
263 ///
264 /// This is not threadsafe at all, so initialization os performed through a
265 /// `Once` primitive (and this function is called from that primitive).
266 fn init() {
267     let mut directives = match os::getenv("RUST_LOG") {
268         Some(spec) => directive::parse_logging_spec(spec),
269         None => Vec::new(),
270     };
271
272     // Sort the provided directives by length of their name, this allows a
273     // little more efficient lookup at runtime.
274     directives.sort_by(|a, b| {
275         let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
276         let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
277         alen.cmp(&blen)
278     });
279
280     let max_level = {
281         let max = directives.iter().max_by(|d| d.level);
282         max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
283     };
284
285     unsafe {
286         LOG_LEVEL = max_level;
287
288         assert!(DIRECTIVES.is_null());
289         DIRECTIVES = cast::transmute(~directives);
290
291         // Schedule the cleanup for this global for when the runtime exits.
292         rt::at_exit(proc() {
293             assert!(!DIRECTIVES.is_null());
294             let _directives: ~Vec<directive::LogDirective> =
295                 cast::transmute(DIRECTIVES);
296             DIRECTIVES = 0 as *Vec<directive::LogDirective>;
297         });
298     }
299 }
300
301 #[cfg(test)]
302 mod tests {
303     use super::enabled;
304     use directive::LogDirective;
305
306     #[test]
307     fn match_full_path() {
308         let dirs = [LogDirective { name: Some(~"crate2"), level: 3 },
309                     LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
310         assert!(enabled(2, "crate1::mod1", dirs.iter()));
311         assert!(!enabled(3, "crate1::mod1", dirs.iter()));
312         assert!(enabled(3, "crate2", dirs.iter()));
313         assert!(!enabled(4, "crate2", dirs.iter()));
314     }
315
316     #[test]
317     fn no_match() {
318         let dirs = [LogDirective { name: Some(~"crate2"), level: 3 },
319                     LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
320         assert!(!enabled(2, "crate3", dirs.iter()));
321     }
322
323     #[test]
324     fn match_beginning() {
325         let dirs = [LogDirective { name: Some(~"crate2"), level: 3 },
326                     LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
327         assert!(enabled(3, "crate2::mod1", dirs.iter()));
328     }
329
330     #[test]
331     fn match_beginning_longest_match() {
332         let dirs = [LogDirective { name: Some(~"crate2"), level: 3 },
333                     LogDirective { name: Some(~"crate2::mod"), level: 4 },
334                     LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
335         assert!(enabled(4, "crate2::mod1", dirs.iter()));
336         assert!(!enabled(4, "crate2", dirs.iter()));
337     }
338
339     #[test]
340     fn match_default() {
341         let dirs = [LogDirective { name: None, level: 3 },
342                     LogDirective { name: Some(~"crate1::mod1"), level: 2 }];
343         assert!(enabled(2, "crate1::mod1", dirs.iter()));
344         assert!(enabled(3, "crate2::mod2", dirs.iter()));
345     }
346
347     #[test]
348     fn zero_level() {
349         let dirs = [LogDirective { name: None, level: 3 },
350                     LogDirective { name: Some(~"crate1::mod1"), level: 0 }];
351         assert!(!enabled(1, "crate1::mod1", dirs.iter()));
352         assert!(enabled(3, "crate2::mod2", dirs.iter()));
353     }
354 }