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