]> git.lizzy.rs Git - rust.git/blob - src/liblog/lib.rs
rollup merge of #20746: dotdash/fix_indent
[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 //! Utilities for program-wide and customizable logging
12 //!
13 //! # Examples
14 //!
15 //! ```
16 //! #[macro_use] extern crate log;
17 //!
18 //! fn main() {
19 //!     debug!("this is a debug {:?}", "message");
20 //!     error!("this is printed by default");
21 //!
22 //!     if log_enabled!(log::INFO) {
23 //!         let x = 3i * 4i; // expensive computation
24 //!         info!("the answer was: {:?}", x);
25 //!     }
26 //! }
27 //! ```
28 //!
29 //! Assumes the binary is `main`:
30 //!
31 //! ```{.bash}
32 //! $ RUST_LOG=error ./main
33 //! ERROR:main: this is printed by default
34 //! ```
35 //!
36 //! ```{.bash}
37 //! $ RUST_LOG=info ./main
38 //! ERROR:main: this is printed by default
39 //! INFO:main: the answer was: 12
40 //! ```
41 //!
42 //! ```{.bash}
43 //! $ RUST_LOG=debug ./main
44 //! DEBUG:main: this is a debug message
45 //! ERROR:main: this is printed by default
46 //! INFO:main: the answer was: 12
47 //! ```
48 //!
49 //! You can also set the log level on a per module basis:
50 //!
51 //! ```{.bash}
52 //! $ RUST_LOG=main=info ./main
53 //! ERROR:main: this is printed by default
54 //! INFO:main: the answer was: 12
55 //! ```
56 //!
57 //! And enable all logging:
58 //!
59 //! ```{.bash}
60 //! $ RUST_LOG=main ./main
61 //! DEBUG:main: this is a debug message
62 //! ERROR:main: this is printed by default
63 //! INFO:main: the answer was: 12
64 //! ```
65 //!
66 //! # Logging Macros
67 //!
68 //! There are five macros that the logging subsystem uses:
69 //!
70 //! * `log!(level, ...)` - the generic logging macro, takes a level as a u32 and any
71 //!                        related `format!` arguments
72 //! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG`
73 //! * `info!(...)` - a macro hard-wired to the log level of `INFO`
74 //! * `warn!(...)` - a macro hard-wired to the log level of `WARN`
75 //! * `error!(...)` - a macro hard-wired to the log level of `ERROR`
76 //!
77 //! All of these macros use the same style of syntax as the `format!` syntax
78 //! extension. Details about the syntax can be found in the documentation of
79 //! `std::fmt` along with the Rust tutorial/manual.
80 //!
81 //! If you want to check at runtime if a given logging level is enabled (e.g. if the
82 //! information you would want to log is expensive to produce), you can use the
83 //! following macro:
84 //!
85 //! * `log_enabled!(level)` - returns true if logging of the given level is enabled
86 //!
87 //! # Enabling logging
88 //!
89 //! Log levels are controlled on a per-module basis, and by default all logging is
90 //! disabled except for `error!` (a log level of 1). Logging is controlled via the
91 //! `RUST_LOG` environment variable. The value of this environment variable is a
92 //! comma-separated list of logging directives. A logging directive is of the form:
93 //!
94 //! ```text
95 //! path::to::module=log_level
96 //! ```
97 //!
98 //! The path to the module is rooted in the name of the crate it was compiled for,
99 //! so if your program is contained in a file `hello.rs`, for example, to turn on
100 //! logging for this file you would use a value of `RUST_LOG=hello`.
101 //! Furthermore, this path is a prefix-search, so all modules nested in the
102 //! specified module will also have logging enabled.
103 //!
104 //! The actual `log_level` is optional to specify. If omitted, all logging will be
105 //! enabled. If specified, the it must be either a numeric in the range of 1-255, or
106 //! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric
107 //! is specified, then all logging less than or equal to that numeral is enabled.
108 //! For example, if logging level 3 is active, error, warn, and info logs will be
109 //! printed, but debug will be omitted.
110 //!
111 //! As the log level for a module is optional, the module to enable logging for is
112 //! also optional. If only a `log_level` is provided, then the global log level for
113 //! all modules is set to this value.
114 //!
115 //! Some examples of valid values of `RUST_LOG` are:
116 //!
117 //! * `hello` turns on all logging for the 'hello' module
118 //! * `info` turns on all info logging
119 //! * `hello=debug` turns on debug logging for 'hello'
120 //! * `hello=3` turns on info logging for 'hello'
121 //! * `hello,std::option` turns on hello, and std's option logging
122 //! * `error,hello=warn` turn on global error logging and also warn for hello
123 //!
124 //! # Filtering results
125 //!
126 //! A RUST_LOG directive may include a regex filter. The syntax is to append `/`
127 //! followed by a regex. Each message is checked against the regex, and is only
128 //! logged if it matches. Note that the matching is done after formatting the log
129 //! string but before adding any logging meta-data. There is a single filter for all
130 //! modules.
131 //!
132 //! Some examples:
133 //!
134 //! * `hello/foo` turns on all logging for the 'hello' module where the log message
135 //! includes 'foo'.
136 //! * `info/f.o` turns on all info logging where the log message includes 'foo',
137 //! 'f1o', 'fao', etc.
138 //! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log
139 //! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc.
140 //! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for
141 //!  hello. In both cases the log message must include a single digit number
142 //!  followed by 'scopes'
143 //!
144 //! # Performance and Side Effects
145 //!
146 //! Each of these macros will expand to code similar to:
147 //!
148 //! ```rust,ignore
149 //! if log_level <= my_module_log_level() {
150 //!     ::log::log(log_level, format!(...));
151 //! }
152 //! ```
153 //!
154 //! What this means is that each of these macros are very cheap at runtime if
155 //! they're turned off (just a load and an integer comparison). This also means that
156 //! if logging is disabled, none of the components of the log will be executed.
157
158 #![crate_name = "log"]
159 #![unstable = "use the crates.io `log` library instead"]
160 #![staged_api]
161 #![crate_type = "rlib"]
162 #![crate_type = "dylib"]
163 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
164        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
165        html_root_url = "http://doc.rust-lang.org/nightly/",
166        html_playground_url = "http://play.rust-lang.org/")]
167
168 #![allow(unknown_features)]
169 #![feature(slicing_syntax)]
170 #![feature(box_syntax)]
171 #![deny(missing_docs)]
172
173 extern crate regex;
174
175 use std::cell::RefCell;
176 use std::fmt;
177 use std::io::LineBufferedWriter;
178 use std::io;
179 use std::mem;
180 use std::os;
181 use std::rt;
182 use std::slice;
183 use std::sync::{Once, ONCE_INIT};
184
185 use regex::Regex;
186
187 use directive::LOG_LEVEL_NAMES;
188
189 #[macro_use]
190 pub mod macros;
191
192 mod directive;
193
194 /// Maximum logging level of a module that can be specified. Common logging
195 /// levels are found in the DEBUG/INFO/WARN/ERROR constants.
196 pub const MAX_LOG_LEVEL: u32 = 255;
197
198 /// The default logging level of a crate if no other is specified.
199 const DEFAULT_LOG_LEVEL: u32 = 1;
200
201 /// An unsafe constant that is the maximum logging level of any module
202 /// specified. This is the first line of defense to determining whether a
203 /// logging statement should be run.
204 static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
205
206 static mut DIRECTIVES: *const Vec<directive::LogDirective> =
207     0 as *const Vec<directive::LogDirective>;
208
209 /// Optional regex filter.
210 static mut FILTER: *const Regex = 0 as *const _;
211
212 /// Debug log level
213 pub const DEBUG: u32 = 4;
214 /// Info log level
215 pub const INFO: u32 = 3;
216 /// Warn log level
217 pub const WARN: u32 = 2;
218 /// Error log level
219 pub const ERROR: u32 = 1;
220
221 thread_local! {
222     static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = {
223         RefCell::new(None)
224     }
225 }
226
227 /// A trait used to represent an interface to a task-local logger. Each task
228 /// can have its own custom logger which can respond to logging messages
229 /// however it likes.
230 pub trait Logger {
231     /// Logs a single message described by the `record`.
232     fn log(&mut self, record: &LogRecord);
233 }
234
235 struct DefaultLogger {
236     handle: LineBufferedWriter<io::stdio::StdWriter>,
237 }
238
239 /// Wraps the log level with fmt implementations.
240 #[derive(Copy, PartialEq, PartialOrd)]
241 pub struct LogLevel(pub u32);
242
243 impl fmt::Show for LogLevel {
244     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
245         fmt::String::fmt(self, fmt)
246     }
247 }
248
249 impl fmt::String for LogLevel {
250     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
251         let LogLevel(level) = *self;
252         match LOG_LEVEL_NAMES.get(level as uint - 1) {
253             Some(ref name) => fmt::String::fmt(name, fmt),
254             None => fmt::String::fmt(&level, fmt)
255         }
256     }
257 }
258
259 impl Logger for DefaultLogger {
260     fn log(&mut self, record: &LogRecord) {
261         match writeln!(&mut self.handle,
262                        "{}:{}: {}",
263                        record.level,
264                        record.module_path,
265                        record.args) {
266             Err(e) => panic!("failed to log: {:?}", e),
267             Ok(()) => {}
268         }
269     }
270 }
271
272 impl Drop for DefaultLogger {
273     fn drop(&mut self) {
274         // FIXME(#12628): is panicking the right thing to do?
275         match self.handle.flush() {
276             Err(e) => panic!("failed to flush a logger: {:?}", e),
277             Ok(()) => {}
278         }
279     }
280 }
281
282 /// This function is called directly by the compiler when using the logging
283 /// macros. This function does not take into account whether the log level
284 /// specified is active or not, it will always log something if this method is
285 /// called.
286 ///
287 /// It is not recommended to call this function directly, rather it should be
288 /// invoked through the logging family of macros.
289 #[doc(hidden)]
290 pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
291     // Test the literal string from args against the current filter, if there
292     // is one.
293     match unsafe { FILTER.as_ref() } {
294         Some(filter) if !filter.is_match(&args.to_string()[]) => return,
295         _ => {}
296     }
297
298     // Completely remove the local logger from TLS in case anyone attempts to
299     // frob the slot while we're doing the logging. This will destroy any logger
300     // set during logging.
301     let mut logger = LOCAL_LOGGER.with(|s| {
302         s.borrow_mut().take()
303     }).unwrap_or_else(|| {
304         box DefaultLogger { handle: io::stderr() } as Box<Logger + Send>
305     });
306     logger.log(&LogRecord {
307         level: LogLevel(level),
308         args: args,
309         file: loc.file,
310         module_path: loc.module_path,
311         line: loc.line,
312     });
313     set_logger(logger);
314 }
315
316 /// Getter for the global log level. This is a function so that it can be called
317 /// safely
318 #[doc(hidden)]
319 #[inline(always)]
320 pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
321
322 /// Replaces the task-local logger with the specified logger, returning the old
323 /// logger.
324 pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
325     let mut l = Some(logger);
326     LOCAL_LOGGER.with(|slot| {
327         mem::replace(&mut *slot.borrow_mut(), l.take())
328     })
329 }
330
331 /// A LogRecord is created by the logging macros, and passed as the only
332 /// argument to Loggers.
333 #[derive(Show)]
334 pub struct LogRecord<'a> {
335
336     /// The module path of where the LogRecord originated.
337     pub module_path: &'a str,
338
339     /// The LogLevel of this record.
340     pub level: LogLevel,
341
342     /// The arguments from the log line.
343     pub args: fmt::Arguments<'a>,
344
345     /// The file of where the LogRecord originated.
346     pub file: &'a str,
347
348     /// The line number of where the LogRecord originated.
349     pub line: uint,
350 }
351
352 #[doc(hidden)]
353 #[derive(Copy)]
354 pub struct LogLocation {
355     pub module_path: &'static str,
356     pub file: &'static str,
357     pub line: uint,
358 }
359
360 /// Tests whether a given module's name is enabled for a particular level of
361 /// logging. This is the second layer of defense about determining whether a
362 /// module's log statement should be emitted or not.
363 #[doc(hidden)]
364 pub fn mod_enabled(level: u32, module: &str) -> bool {
365     static INIT: Once = ONCE_INIT;
366     INIT.call_once(init);
367
368     // It's possible for many threads are in this function, only one of them
369     // will perform the global initialization, but all of them will need to check
370     // again to whether they should really be here or not. Hence, despite this
371     // check being expanded manually in the logging macro, this function checks
372     // the log level again.
373     if level > unsafe { LOG_LEVEL } { return false }
374
375     // This assertion should never get tripped unless we're in an at_exit
376     // handler after logging has been torn down and a logging attempt was made.
377     assert!(unsafe { !DIRECTIVES.is_null() });
378
379     enabled(level, module, unsafe { (*DIRECTIVES).iter() })
380 }
381
382 fn enabled(level: u32,
383            module: &str,
384            iter: slice::Iter<directive::LogDirective>)
385            -> bool {
386     // Search for the longest match, the vector is assumed to be pre-sorted.
387     for directive in iter.rev() {
388         match directive.name {
389             Some(ref name) if !module.starts_with(&name[]) => {},
390             Some(..) | None => {
391                 return level <= directive.level
392             }
393         }
394     }
395     level <= DEFAULT_LOG_LEVEL
396 }
397
398 /// Initialize logging for the current process.
399 ///
400 /// This is not threadsafe at all, so initialization is performed through a
401 /// `Once` primitive (and this function is called from that primitive).
402 fn init() {
403     let (mut directives, filter) = match os::getenv("RUST_LOG") {
404         Some(spec) => directive::parse_logging_spec(&spec[]),
405         None => (Vec::new(), None),
406     };
407
408     // Sort the provided directives by length of their name, this allows a
409     // little more efficient lookup at runtime.
410     directives.sort_by(|a, b| {
411         let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
412         let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
413         alen.cmp(&blen)
414     });
415
416     let max_level = {
417         let max = directives.iter().max_by(|d| d.level);
418         max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
419     };
420
421     unsafe {
422         LOG_LEVEL = max_level;
423
424         assert!(FILTER.is_null());
425         match filter {
426             Some(f) => FILTER = mem::transmute(box f),
427             None => {}
428         }
429
430         assert!(DIRECTIVES.is_null());
431         DIRECTIVES = mem::transmute(box directives);
432
433         // Schedule the cleanup for the globals for when the runtime exits.
434         rt::at_exit(move |:| {
435             assert!(!DIRECTIVES.is_null());
436             let _directives: Box<Vec<directive::LogDirective>> =
437                 mem::transmute(DIRECTIVES);
438             DIRECTIVES = 0 as *const Vec<directive::LogDirective>;
439
440             if !FILTER.is_null() {
441                 let _filter: Box<Regex> = mem::transmute(FILTER);
442                 FILTER = 0 as *const _;
443             }
444         });
445     }
446 }
447
448 #[cfg(test)]
449 mod tests {
450     use super::enabled;
451     use directive::LogDirective;
452
453     #[test]
454     fn match_full_path() {
455         let dirs = [
456             LogDirective {
457                 name: Some("crate2".to_string()),
458                 level: 3
459             },
460             LogDirective {
461                 name: Some("crate1::mod1".to_string()),
462                 level: 2
463             }
464         ];
465         assert!(enabled(2, "crate1::mod1", dirs.iter()));
466         assert!(!enabled(3, "crate1::mod1", dirs.iter()));
467         assert!(enabled(3, "crate2", dirs.iter()));
468         assert!(!enabled(4, "crate2", dirs.iter()));
469     }
470
471     #[test]
472     fn no_match() {
473         let dirs = [
474             LogDirective { name: Some("crate2".to_string()), level: 3 },
475             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
476         ];
477         assert!(!enabled(2, "crate3", dirs.iter()));
478     }
479
480     #[test]
481     fn match_beginning() {
482         let dirs = [
483             LogDirective { name: Some("crate2".to_string()), level: 3 },
484             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
485         ];
486         assert!(enabled(3, "crate2::mod1", dirs.iter()));
487     }
488
489     #[test]
490     fn match_beginning_longest_match() {
491         let dirs = [
492             LogDirective { name: Some("crate2".to_string()), level: 3 },
493             LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
494             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
495         ];
496         assert!(enabled(4, "crate2::mod1", dirs.iter()));
497         assert!(!enabled(4, "crate2", dirs.iter()));
498     }
499
500     #[test]
501     fn match_default() {
502         let dirs = [
503             LogDirective { name: None, level: 3 },
504             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
505         ];
506         assert!(enabled(2, "crate1::mod1", dirs.iter()));
507         assert!(enabled(3, "crate2::mod2", dirs.iter()));
508     }
509
510     #[test]
511     fn zero_level() {
512         let dirs = [
513             LogDirective { name: None, level: 3 },
514             LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
515         ];
516         assert!(!enabled(1, "crate1::mod1", dirs.iter()));
517         assert!(enabled(3, "crate2::mod2", dirs.iter()));
518     }
519 }