]> git.lizzy.rs Git - rust.git/blob - src/liblog/lib.rs
Register new snapshots
[rust.git] / src / liblog / lib.rs
1 // Copyright 2014 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(plugin, 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 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 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 ```text
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 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 ```text
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.11.0-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://doc.rust-lang.org/",
115        html_playground_url = "http://play.rust-lang.org/")]
116
117 #![feature(macro_rules)]
118 #![deny(missing_doc)]
119
120 use std::fmt;
121 use std::io::LineBufferedWriter;
122 use std::io;
123 use std::mem;
124 use std::os;
125 use std::rt;
126 use std::slice;
127 use std::sync::{Once, ONCE_INIT};
128
129 use directive::LOG_LEVEL_NAMES;
130
131 pub mod macros;
132 mod directive;
133
134 /// Maximum logging level of a module that can be specified. Common logging
135 /// levels are found in the DEBUG/INFO/WARN/ERROR constants.
136 pub static MAX_LOG_LEVEL: u32 = 255;
137
138 /// The default logging level of a crate if no other is specified.
139 static DEFAULT_LOG_LEVEL: u32 = 1;
140
141 /// An unsafe constant that is the maximum logging level of any module
142 /// specified. This is the first line of defense to determining whether a
143 /// logging statement should be run.
144 static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
145
146 static mut DIRECTIVES: *Vec<directive::LogDirective> =
147     0 as *Vec<directive::LogDirective>;
148
149 /// Debug log level
150 pub static DEBUG: u32 = 4;
151 /// Info log level
152 pub static INFO: u32 = 3;
153 /// Warn log level
154 pub static WARN: u32 = 2;
155 /// Error log level
156 pub static ERROR: u32 = 1;
157
158 local_data_key!(local_logger: Box<Logger + Send>)
159
160 /// A trait used to represent an interface to a task-local logger. Each task
161 /// can have its own custom logger which can respond to logging messages
162 /// however it likes.
163 pub trait Logger {
164     /// Logs a single message described by the `record`.
165     fn log(&mut self, record: &LogRecord);
166 }
167
168 struct DefaultLogger {
169     handle: LineBufferedWriter<io::stdio::StdWriter>,
170 }
171
172 /// Wraps the log level with fmt implementations.
173 #[deriving(PartialEq, PartialOrd)]
174 pub struct LogLevel(pub u32);
175
176 impl fmt::Show for LogLevel {
177     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
178         let LogLevel(level) = *self;
179         match LOG_LEVEL_NAMES.get(level as uint - 1) {
180             Some(name) => name.fmt(fmt),
181             None => level.fmt(fmt)
182         }
183     }
184 }
185
186 impl fmt::Signed for LogLevel {
187     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
188         let LogLevel(level) = *self;
189         write!(fmt, "{}", level)
190     }
191 }
192
193 impl Logger for DefaultLogger {
194     fn log(&mut self, record: &LogRecord) {
195         match writeln!(&mut self.handle,
196                        "{}:{}: {}",
197                        record.level,
198                        record.module_path,
199                        record.args) {
200             Err(e) => fail!("failed to log: {}", e),
201             Ok(()) => {}
202         }
203     }
204 }
205
206 impl Drop for DefaultLogger {
207     fn drop(&mut self) {
208         // FIXME(#12628): is failure the right thing to do?
209         match self.handle.flush() {
210             Err(e) => fail!("failed to flush a logger: {}", e),
211             Ok(()) => {}
212         }
213     }
214 }
215
216 /// This function is called directly by the compiler when using the logging
217 /// macros. This function does not take into account whether the log level
218 /// specified is active or not, it will always log something if this method is
219 /// called.
220 ///
221 /// It is not recommended to call this function directly, rather it should be
222 /// invoked through the logging family of macros.
223 #[doc(hidden)]
224 pub fn log(level: u32, loc: &'static LogLocation, args: &fmt::Arguments) {
225     // Completely remove the local logger from TLS in case anyone attempts to
226     // frob the slot while we're doing the logging. This will destroy any logger
227     // set during logging.
228     let mut logger = local_logger.replace(None).unwrap_or_else(|| {
229         box DefaultLogger { handle: io::stderr() } as Box<Logger + Send>
230     });
231     logger.log(&LogRecord {
232         level: LogLevel(level),
233         args: args,
234         file: loc.file,
235         module_path: loc.module_path,
236         line: loc.line,
237     });
238     local_logger.replace(Some(logger));
239 }
240
241 /// Getter for the global log level. This is a function so that it can be called
242 /// safely
243 #[doc(hidden)]
244 #[inline(always)]
245 pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
246
247 /// Replaces the task-local logger with the specified logger, returning the old
248 /// logger.
249 pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
250     local_logger.replace(Some(logger))
251 }
252
253 /// A LogRecord is created by the logging macros, and passed as the only
254 /// argument to Loggers.
255 #[deriving(Show)]
256 pub struct LogRecord<'a> {
257
258     /// The module path of where the LogRecord originated.
259     pub module_path: &'a str,
260
261     /// The LogLevel of this record.
262     pub level: LogLevel,
263
264     /// The arguments from the log line.
265     pub args: &'a fmt::Arguments<'a>,
266
267     /// The file of where the LogRecord originated.
268     pub file: &'a str,
269
270     /// The line number of where the LogRecord originated.
271     pub line: uint,
272 }
273
274 #[doc(hidden)]
275 pub struct LogLocation {
276     pub module_path: &'static str,
277     pub file: &'static str,
278     pub line: uint,
279 }
280
281 /// Tests whether a given module's name is enabled for a particular level of
282 /// logging. This is the second layer of defense about determining whether a
283 /// module's log statement should be emitted or not.
284 #[doc(hidden)]
285 pub fn mod_enabled(level: u32, module: &str) -> bool {
286     static mut INIT: Once = ONCE_INIT;
287     unsafe { INIT.doit(init); }
288
289     // It's possible for many threads are in this function, only one of them
290     // will peform the global initialization, but all of them will need to check
291     // again to whether they should really be here or not. Hence, despite this
292     // check being expanded manually in the logging macro, this function checks
293     // the log level again.
294     if level > unsafe { LOG_LEVEL } { return false }
295
296     // This assertion should never get tripped unless we're in an at_exit
297     // handler after logging has been torn down and a logging attempt was made.
298     assert!(unsafe { !DIRECTIVES.is_null() });
299
300     enabled(level, module, unsafe { (*DIRECTIVES).iter() })
301 }
302
303 fn enabled(level: u32,
304            module: &str,
305            iter: slice::Items<directive::LogDirective>)
306            -> bool {
307     // Search for the longest match, the vector is assumed to be pre-sorted.
308     for directive in iter.rev() {
309         match directive.name {
310             Some(ref name) if !module.starts_with(name.as_slice()) => {},
311             Some(..) | None => {
312                 return level <= directive.level
313             }
314         }
315     }
316     level <= DEFAULT_LOG_LEVEL
317 }
318
319 /// Initialize logging for the current process.
320 ///
321 /// This is not threadsafe at all, so initialization os performed through a
322 /// `Once` primitive (and this function is called from that primitive).
323 fn init() {
324     let mut directives = match os::getenv("RUST_LOG") {
325         Some(spec) => directive::parse_logging_spec(spec.as_slice()),
326         None => Vec::new(),
327     };
328
329     // Sort the provided directives by length of their name, this allows a
330     // little more efficient lookup at runtime.
331     directives.sort_by(|a, b| {
332         let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
333         let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
334         alen.cmp(&blen)
335     });
336
337     let max_level = {
338         let max = directives.iter().max_by(|d| d.level);
339         max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
340     };
341
342     unsafe {
343         LOG_LEVEL = max_level;
344
345         assert!(DIRECTIVES.is_null());
346         DIRECTIVES = mem::transmute(box directives);
347
348         // Schedule the cleanup for this global for when the runtime exits.
349         rt::at_exit(proc() {
350             assert!(!DIRECTIVES.is_null());
351             let _directives: Box<Vec<directive::LogDirective>> =
352                 mem::transmute(DIRECTIVES);
353             DIRECTIVES = 0 as *Vec<directive::LogDirective>;
354         });
355     }
356 }
357
358 #[cfg(test)]
359 mod tests {
360     use super::enabled;
361     use directive::LogDirective;
362
363     #[test]
364     fn match_full_path() {
365         let dirs = [
366             LogDirective {
367                 name: Some("crate2".to_string()),
368                 level: 3
369             },
370             LogDirective {
371                 name: Some("crate1::mod1".to_string()),
372                 level: 2
373             }
374         ];
375         assert!(enabled(2, "crate1::mod1", dirs.iter()));
376         assert!(!enabled(3, "crate1::mod1", dirs.iter()));
377         assert!(enabled(3, "crate2", dirs.iter()));
378         assert!(!enabled(4, "crate2", dirs.iter()));
379     }
380
381     #[test]
382     fn no_match() {
383         let dirs = [
384             LogDirective { name: Some("crate2".to_string()), level: 3 },
385             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
386         ];
387         assert!(!enabled(2, "crate3", dirs.iter()));
388     }
389
390     #[test]
391     fn match_beginning() {
392         let dirs = [
393             LogDirective { name: Some("crate2".to_string()), level: 3 },
394             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
395         ];
396         assert!(enabled(3, "crate2::mod1", dirs.iter()));
397     }
398
399     #[test]
400     fn match_beginning_longest_match() {
401         let dirs = [
402             LogDirective { name: Some("crate2".to_string()), level: 3 },
403             LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
404             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
405         ];
406         assert!(enabled(4, "crate2::mod1", dirs.iter()));
407         assert!(!enabled(4, "crate2", dirs.iter()));
408     }
409
410     #[test]
411     fn match_default() {
412         let dirs = [
413             LogDirective { name: None, level: 3 },
414             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
415         ];
416         assert!(enabled(2, "crate1::mod1", dirs.iter()));
417         assert!(enabled(3, "crate2::mod2", dirs.iter()));
418     }
419
420     #[test]
421     fn zero_level() {
422         let dirs = [
423             LogDirective { name: None, level: 3 },
424             LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
425         ];
426         assert!(!enabled(1, "crate1::mod1", dirs.iter()));
427         assert!(enabled(3, "crate2::mod2", dirs.iter()));
428     }
429 }