]> git.lizzy.rs Git - rust.git/blob - src/liblog/lib.rs
core: Split apart the global `core` feature
[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 = 3 * 4; // 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 string filter. The syntax is to append
127 //! `/` followed by a string. Each message is checked against the string and is
128 //! only logged if it contains the string. Note that the matching is done after
129 //! formatting the log string but before adding any logging meta-data. There is
130 //! a single filter for all 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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
159 #![cfg_attr(stage0, feature(custom_attribute))]
160 #![crate_name = "log"]
161 #![unstable(feature = "rustc_private",
162             reason = "use the crates.io `log` library instead")]
163 #![staged_api]
164 #![crate_type = "rlib"]
165 #![crate_type = "dylib"]
166 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
167        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
168        html_root_url = "http://doc.rust-lang.org/nightly/",
169        html_playground_url = "http://play.rust-lang.org/")]
170 #![deny(missing_docs)]
171
172 #![feature(alloc)]
173 #![feature(staged_api)]
174 #![feature(box_syntax)]
175 #![feature(iter_cmp)]
176 #![feature(std_misc)]
177
178 use std::boxed;
179 use std::cell::RefCell;
180 use std::fmt;
181 use std::io::{self, Stderr};
182 use std::io::prelude::*;
183 use std::mem;
184 use std::env;
185 use std::rt;
186 use std::slice;
187 use std::sync::{Once, StaticMutex};
188
189 use directive::LOG_LEVEL_NAMES;
190
191 #[macro_use]
192 pub mod macros;
193
194 mod directive;
195
196 /// Maximum logging level of a module that can be specified. Common logging
197 /// levels are found in the DEBUG/INFO/WARN/ERROR constants.
198 pub const MAX_LOG_LEVEL: u32 = 255;
199
200 /// The default logging level of a crate if no other is specified.
201 const DEFAULT_LOG_LEVEL: u32 = 1;
202
203 static LOCK: StaticMutex = StaticMutex::new();
204
205 /// An unsafe constant that is the maximum logging level of any module
206 /// specified. This is the first line of defense to determining whether a
207 /// logging statement should be run.
208 static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
209
210 static mut DIRECTIVES: *mut Vec<directive::LogDirective> =
211     0 as *mut Vec<directive::LogDirective>;
212
213 /// Optional filter.
214 static mut FILTER: *mut String = 0 as *mut _;
215
216 /// Debug log level
217 pub const DEBUG: u32 = 4;
218 /// Info log level
219 pub const INFO: u32 = 3;
220 /// Warn log level
221 pub const WARN: u32 = 2;
222 /// Error log level
223 pub const ERROR: u32 = 1;
224
225 thread_local! {
226     static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = {
227         RefCell::new(None)
228     }
229 }
230
231 /// A trait used to represent an interface to a thread-local logger. Each thread
232 /// can have its own custom logger which can respond to logging messages
233 /// however it likes.
234 pub trait Logger {
235     /// Logs a single message described by the `record`.
236     fn log(&mut self, record: &LogRecord);
237 }
238
239 struct DefaultLogger { handle: Stderr }
240
241 /// Wraps the log level with fmt implementations.
242 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
243 pub struct LogLevel(pub u32);
244
245 impl fmt::Display for LogLevel {
246     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
247         let LogLevel(level) = *self;
248         match LOG_LEVEL_NAMES.get(level as usize - 1) {
249             Some(ref name) => fmt::Display::fmt(name, fmt),
250             None => fmt::Display::fmt(&level, fmt)
251         }
252     }
253 }
254
255 impl Logger for DefaultLogger {
256     fn log(&mut self, record: &LogRecord) {
257         match writeln!(&mut self.handle,
258                        "{}:{}: {}",
259                        record.level,
260                        record.module_path,
261                        record.args) {
262             Err(e) => panic!("failed to log: {:?}", e),
263             Ok(()) => {}
264         }
265     }
266 }
267
268 impl Drop for DefaultLogger {
269     fn drop(&mut self) {
270         // FIXME(#12628): is panicking the right thing to do?
271         match self.handle.flush() {
272             Err(e) => panic!("failed to flush a logger: {:?}", e),
273             Ok(()) => {}
274         }
275     }
276 }
277
278 /// This function is called directly by the compiler when using the logging
279 /// macros. This function does not take into account whether the log level
280 /// specified is active or not, it will always log something if this method is
281 /// called.
282 ///
283 /// It is not recommended to call this function directly, rather it should be
284 /// invoked through the logging family of macros.
285 #[doc(hidden)]
286 pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
287     // Test the literal string from args against the current filter, if there
288     // is one.
289     unsafe {
290         let _g = LOCK.lock();
291         match FILTER as usize {
292             0 => {}
293             1 => panic!("cannot log after main thread has exited"),
294             n => {
295                 let filter = mem::transmute::<_, &String>(n);
296                 if !args.to_string().contains(&filter[..]) {
297                     return
298                 }
299             }
300         }
301     }
302
303     // Completely remove the local logger from TLS in case anyone attempts to
304     // frob the slot while we're doing the logging. This will destroy any logger
305     // set during logging.
306     let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| {
307         s.borrow_mut().take()
308     }).unwrap_or_else(|| {
309         box DefaultLogger { handle: io::stderr() }
310     });
311     logger.log(&LogRecord {
312         level: LogLevel(level),
313         args: args,
314         file: loc.file,
315         module_path: loc.module_path,
316         line: loc.line,
317     });
318     set_logger(logger);
319 }
320
321 /// Getter for the global log level. This is a function so that it can be called
322 /// safely
323 #[doc(hidden)]
324 #[inline(always)]
325 pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
326
327 /// Replaces the thread-local logger with the specified logger, returning the old
328 /// logger.
329 pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
330     let mut l = Some(logger);
331     LOCAL_LOGGER.with(|slot| {
332         mem::replace(&mut *slot.borrow_mut(), l.take())
333     })
334 }
335
336 /// A LogRecord is created by the logging macros, and passed as the only
337 /// argument to Loggers.
338 #[derive(Debug)]
339 pub struct LogRecord<'a> {
340
341     /// The module path of where the LogRecord originated.
342     pub module_path: &'a str,
343
344     /// The LogLevel of this record.
345     pub level: LogLevel,
346
347     /// The arguments from the log line.
348     pub args: fmt::Arguments<'a>,
349
350     /// The file of where the LogRecord originated.
351     pub file: &'a str,
352
353     /// The line number of where the LogRecord originated.
354     pub line: u32,
355 }
356
357 #[doc(hidden)]
358 #[derive(Copy, Clone)]
359 pub struct LogLocation {
360     pub module_path: &'static str,
361     pub file: &'static str,
362     pub line: u32,
363 }
364
365 /// Tests whether a given module's name is enabled for a particular level of
366 /// logging. This is the second layer of defense about determining whether a
367 /// module's log statement should be emitted or not.
368 #[doc(hidden)]
369 pub fn mod_enabled(level: u32, module: &str) -> bool {
370     static INIT: Once = Once::new();
371     INIT.call_once(init);
372
373     // It's possible for many threads are in this function, only one of them
374     // will perform the global initialization, but all of them will need to check
375     // again to whether they should really be here or not. Hence, despite this
376     // check being expanded manually in the logging macro, this function checks
377     // the log level again.
378     if level > unsafe { LOG_LEVEL } { return false }
379
380     // This assertion should never get tripped unless we're in an at_exit
381     // handler after logging has been torn down and a logging attempt was made.
382
383     let _g = LOCK.lock();
384     unsafe {
385         assert!(DIRECTIVES as usize != 0);
386         assert!(DIRECTIVES as usize != 1,
387                 "cannot log after the main thread has exited");
388
389         enabled(level, module, (*DIRECTIVES).iter())
390     }
391 }
392
393 fn enabled(level: u32,
394            module: &str,
395            iter: slice::Iter<directive::LogDirective>)
396            -> bool {
397     // Search for the longest match, the vector is assumed to be pre-sorted.
398     for directive in iter.rev() {
399         match directive.name {
400             Some(ref name) if !module.starts_with(&name[..]) => {},
401             Some(..) | None => {
402                 return level <= directive.level
403             }
404         }
405     }
406     level <= DEFAULT_LOG_LEVEL
407 }
408
409 /// Initialize logging for the current process.
410 ///
411 /// This is not threadsafe at all, so initialization is performed through a
412 /// `Once` primitive (and this function is called from that primitive).
413 fn init() {
414     let (mut directives, filter) = match env::var("RUST_LOG") {
415         Ok(spec) => directive::parse_logging_spec(&spec[..]),
416         Err(..) => (Vec::new(), None),
417     };
418
419     // Sort the provided directives by length of their name, this allows a
420     // little more efficient lookup at runtime.
421     directives.sort_by(|a, b| {
422         let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
423         let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
424         alen.cmp(&blen)
425     });
426
427     let max_level = {
428         let max = directives.iter().max_by(|d| d.level);
429         max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
430     };
431
432     unsafe {
433         LOG_LEVEL = max_level;
434
435         assert!(FILTER.is_null());
436         match filter {
437             Some(f) => FILTER = boxed::into_raw(box f),
438             None => {}
439         }
440
441         assert!(DIRECTIVES.is_null());
442         DIRECTIVES = boxed::into_raw(box directives);
443
444         // Schedule the cleanup for the globals for when the runtime exits.
445         let _ = rt::at_exit(move || {
446             let _g = LOCK.lock();
447             assert!(!DIRECTIVES.is_null());
448             let _directives = Box::from_raw(DIRECTIVES);
449             DIRECTIVES = 1 as *mut _;
450
451             if !FILTER.is_null() {
452                 let _filter = Box::from_raw(FILTER);
453                 FILTER = 1 as *mut _;
454             }
455         });
456     }
457 }
458
459 #[cfg(test)]
460 mod tests {
461     use super::enabled;
462     use directive::LogDirective;
463
464     #[test]
465     fn match_full_path() {
466         let dirs = [
467             LogDirective {
468                 name: Some("crate2".to_string()),
469                 level: 3
470             },
471             LogDirective {
472                 name: Some("crate1::mod1".to_string()),
473                 level: 2
474             }
475         ];
476         assert!(enabled(2, "crate1::mod1", dirs.iter()));
477         assert!(!enabled(3, "crate1::mod1", dirs.iter()));
478         assert!(enabled(3, "crate2", dirs.iter()));
479         assert!(!enabled(4, "crate2", dirs.iter()));
480     }
481
482     #[test]
483     fn no_match() {
484         let dirs = [
485             LogDirective { name: Some("crate2".to_string()), level: 3 },
486             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
487         ];
488         assert!(!enabled(2, "crate3", dirs.iter()));
489     }
490
491     #[test]
492     fn match_beginning() {
493         let dirs = [
494             LogDirective { name: Some("crate2".to_string()), level: 3 },
495             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
496         ];
497         assert!(enabled(3, "crate2::mod1", dirs.iter()));
498     }
499
500     #[test]
501     fn match_beginning_longest_match() {
502         let dirs = [
503             LogDirective { name: Some("crate2".to_string()), level: 3 },
504             LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
505             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
506         ];
507         assert!(enabled(4, "crate2::mod1", dirs.iter()));
508         assert!(!enabled(4, "crate2", dirs.iter()));
509     }
510
511     #[test]
512     fn match_default() {
513         let dirs = [
514             LogDirective { name: None, level: 3 },
515             LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
516         ];
517         assert!(enabled(2, "crate1::mod1", dirs.iter()));
518         assert!(enabled(3, "crate2::mod2", dirs.iter()));
519     }
520
521     #[test]
522     fn zero_level() {
523         let dirs = [
524             LogDirective { name: None, level: 3 },
525             LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
526         ];
527         assert!(!enabled(1, "crate1::mod1", dirs.iter()));
528         assert!(enabled(3, "crate2::mod2", dirs.iter()));
529     }
530 }