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.
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.
11 //! Utilities for program-wide and customizable logging
16 //! # #![feature(rustc_private)]
17 //! #[macro_use] extern crate log;
20 //! debug!("this is a debug {:?}", "message");
21 //! error!("this is printed by default");
23 //! if log_enabled!(log::INFO) {
24 //! let x = 3 * 4; // expensive computation
25 //! info!("the answer was: {:?}", x);
30 //! Assumes the binary is `main`:
33 //! $ RUST_LOG=error ./main
34 //! ERROR:main: this is printed by default
38 //! $ RUST_LOG=info ./main
39 //! ERROR:main: this is printed by default
40 //! INFO:main: the answer was: 12
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
50 //! You can also set the log level on a per module basis:
53 //! $ RUST_LOG=main=info ./main
54 //! ERROR:main: this is printed by default
55 //! INFO:main: the answer was: 12
58 //! And enable all logging:
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
69 //! There are five macros that the logging subsystem uses:
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`
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.
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
86 //! * `log_enabled!(level)` - returns true if logging of the given level is enabled
88 //! # Enabling logging
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:
96 //! path::to::module=log_level
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.
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.
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.
116 //! Some examples of valid values of `RUST_LOG` are:
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
125 //! # Filtering results
127 //! A RUST_LOG directive may include a string filter. The syntax is to append
128 //! `/` followed by a string. Each message is checked against the string and is
129 //! only logged if it contains the string. Note that the matching is done after
130 //! formatting the log string but before adding any logging meta-data. There is
131 //! a single filter for all modules.
135 //! * `hello/foo` turns on all logging for the 'hello' module where the log message
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'
145 //! # Performance and Side Effects
147 //! Each of these macros will expand to code similar to:
150 //! if log_level <= my_module_log_level() {
151 //! ::log::log(log_level, format!(...));
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.
159 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
160 #![cfg_attr(stage0, feature(custom_attribute))]
161 #![crate_name = "log"]
162 #![unstable(feature = "rustc_private",
163 reason = "use the crates.io `log` library instead",
166 #![crate_type = "rlib"]
167 #![crate_type = "dylib"]
168 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
169 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
170 html_root_url = "https://doc.rust-lang.org/nightly/",
171 html_playground_url = "https://play.rust-lang.org/",
172 test(attr(deny(warnings))))]
173 #![deny(missing_docs)]
175 #![feature(box_syntax)]
176 #![feature(const_fn)]
177 #![feature(iter_cmp)]
178 #![feature(staged_api)]
179 #![feature(static_mutex)]
181 use std::cell::RefCell;
183 use std::io::{self, Stderr};
184 use std::io::prelude::*;
189 use std::sync::{Once, StaticMutex};
191 use directive::LOG_LEVEL_NAMES;
198 /// Maximum logging level of a module that can be specified. Common logging
199 /// levels are found in the DEBUG/INFO/WARN/ERROR constants.
200 pub const MAX_LOG_LEVEL: u32 = 255;
202 /// The default logging level of a crate if no other is specified.
203 const DEFAULT_LOG_LEVEL: u32 = 1;
205 static LOCK: StaticMutex = StaticMutex::new();
207 /// An unsafe constant that is the maximum logging level of any module
208 /// specified. This is the first line of defense to determining whether a
209 /// logging statement should be run.
210 static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
212 static mut DIRECTIVES: *mut Vec<directive::LogDirective> = ptr::null_mut();
215 static mut FILTER: *mut String = ptr::null_mut();
218 pub const DEBUG: u32 = 4;
220 pub const INFO: u32 = 3;
222 pub const WARN: u32 = 2;
224 pub const ERROR: u32 = 1;
227 static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = {
232 /// A trait used to represent an interface to a thread-local logger. Each thread
233 /// can have its own custom logger which can respond to logging messages
234 /// however it likes.
236 /// Logs a single message described by the `record`.
237 fn log(&mut self, record: &LogRecord);
240 struct DefaultLogger {
244 /// Wraps the log level with fmt implementations.
245 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
246 pub struct LogLevel(pub u32);
248 impl fmt::Display for LogLevel {
249 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
250 let LogLevel(level) = *self;
251 match LOG_LEVEL_NAMES.get(level as usize - 1) {
252 Some(ref name) => fmt::Display::fmt(name, fmt),
253 None => fmt::Display::fmt(&level, fmt),
258 impl Logger for DefaultLogger {
259 fn log(&mut self, record: &LogRecord) {
260 match writeln!(&mut self.handle,
265 Err(e) => panic!("failed to log: {:?}", e),
271 impl Drop for DefaultLogger {
273 // FIXME(#12628): is panicking the right thing to do?
274 match self.handle.flush() {
275 Err(e) => panic!("failed to flush a logger: {:?}", e),
281 /// This function is called directly by the compiler when using the logging
282 /// macros. This function does not take into account whether the log level
283 /// specified is active or not, it will always log something if this method is
286 /// It is not recommended to call this function directly, rather it should be
287 /// invoked through the logging family of macros.
289 pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
290 // Test the literal string from args against the current filter, if there
293 let _g = LOCK.lock();
294 match FILTER as usize {
297 let filter = mem::transmute::<_, &String>(n);
298 if !args.to_string().contains(filter) {
305 // Completely remove the local logger from TLS in case anyone attempts to
306 // frob the slot while we're doing the logging. This will destroy any logger
307 // set during logging.
308 let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| s.borrow_mut().take())
310 box DefaultLogger { handle: io::stderr() }
312 logger.log(&LogRecord {
313 level: LogLevel(level),
316 module_path: loc.module_path,
322 /// Getter for the global log level. This is a function so that it can be called
326 pub fn log_level() -> u32 {
330 /// Replaces the thread-local logger with the specified logger, returning the old
332 pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
333 LOCAL_LOGGER.with(|slot| mem::replace(&mut *slot.borrow_mut(), Some(logger)))
336 /// A LogRecord is created by the logging macros, and passed as the only
337 /// argument to Loggers.
339 pub struct LogRecord<'a> {
340 /// The module path of where the LogRecord originated.
341 pub module_path: &'a str,
343 /// The LogLevel of this record.
346 /// The arguments from the log line.
347 pub args: fmt::Arguments<'a>,
349 /// The file of where the LogRecord originated.
352 /// The line number of where the LogRecord originated.
357 #[derive(Copy, Clone)]
358 pub struct LogLocation {
359 pub module_path: &'static str,
360 pub file: &'static str,
364 /// Tests whether a given module's name is enabled for a particular level of
365 /// logging. This is the second layer of defense about determining whether a
366 /// module's log statement should be emitted or not.
368 pub fn mod_enabled(level: u32, module: &str) -> bool {
369 static INIT: Once = Once::new();
370 INIT.call_once(init);
372 // It's possible for many threads are in this function, only one of them
373 // will perform the global initialization, but all of them will need to check
374 // again to whether they should really be here or not. Hence, despite this
375 // check being expanded manually in the logging macro, this function checks
376 // the log level again.
377 if level > unsafe { LOG_LEVEL } {
381 // This assertion should never get tripped unless we're in an at_exit
382 // handler after logging has been torn down and a logging attempt was made.
384 let _g = LOCK.lock();
386 assert!(DIRECTIVES as usize != 0);
387 enabled(level, module, (*DIRECTIVES).iter())
391 fn enabled(level: u32, module: &str, iter: slice::Iter<directive::LogDirective>) -> bool {
392 // Search for the longest match, the vector is assumed to be pre-sorted.
393 for directive in iter.rev() {
394 match directive.name {
395 Some(ref name) if !module.starts_with(&name[..]) => {}
396 Some(..) | None => return level <= directive.level,
399 level <= DEFAULT_LOG_LEVEL
402 /// Initialize logging for the current process.
404 /// This is not threadsafe at all, so initialization is performed through a
405 /// `Once` primitive (and this function is called from that primitive).
407 let (mut directives, filter) = match env::var("RUST_LOG") {
408 Ok(spec) => directive::parse_logging_spec(&spec[..]),
409 Err(..) => (Vec::new(), None),
412 // Sort the provided directives by length of their name, this allows a
413 // little more efficient lookup at runtime.
414 directives.sort_by(|a, b| {
415 let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
416 let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
421 let max = directives.iter().max_by(|d| d.level);
422 max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
426 LOG_LEVEL = max_level;
428 assert!(FILTER.is_null());
430 Some(f) => FILTER = Box::into_raw(box f),
434 assert!(DIRECTIVES.is_null());
435 DIRECTIVES = Box::into_raw(box directives);
442 use directive::LogDirective;
445 fn match_full_path() {
446 let dirs = [LogDirective {
447 name: Some("crate2".to_string()),
451 name: Some("crate1::mod1".to_string()),
454 assert!(enabled(2, "crate1::mod1", dirs.iter()));
455 assert!(!enabled(3, "crate1::mod1", dirs.iter()));
456 assert!(enabled(3, "crate2", dirs.iter()));
457 assert!(!enabled(4, "crate2", dirs.iter()));
462 let dirs = [LogDirective {
463 name: Some("crate2".to_string()),
467 name: Some("crate1::mod1".to_string()),
470 assert!(!enabled(2, "crate3", dirs.iter()));
474 fn match_beginning() {
475 let dirs = [LogDirective {
476 name: Some("crate2".to_string()),
480 name: Some("crate1::mod1".to_string()),
483 assert!(enabled(3, "crate2::mod1", dirs.iter()));
487 fn match_beginning_longest_match() {
488 let dirs = [LogDirective {
489 name: Some("crate2".to_string()),
493 name: Some("crate2::mod".to_string()),
497 name: Some("crate1::mod1".to_string()),
500 assert!(enabled(4, "crate2::mod1", dirs.iter()));
501 assert!(!enabled(4, "crate2", dirs.iter()));
506 let dirs = [LogDirective {
511 name: Some("crate1::mod1".to_string()),
514 assert!(enabled(2, "crate1::mod1", dirs.iter()));
515 assert!(enabled(3, "crate2::mod2", dirs.iter()));
520 let dirs = [LogDirective {
525 name: Some("crate1::mod1".to_string()),
528 assert!(!enabled(1, "crate1::mod1", dirs.iter()));
529 assert!(enabled(3, "crate2::mod2", dirs.iter()));