Removed "stuttering" of types, like LogLevel -> Level.

The affected enums, structs, and functions include:
- LogLevel
- LogLevelFilter
- LogRecord
- LogMetadata
- LogLocation
- MaxLogLevelFilter (now MaxLevelFilter)
- max_log_level (now max_level)
This commit is contained in:
Ottavio Hartman 2017-05-21 15:46:12 -04:00
parent cf501f6375
commit d4748011fa
5 changed files with 318 additions and 318 deletions

152
env/src/lib.rs vendored
View File

@ -17,7 +17,7 @@
//! #[macro_use] extern crate log;
//! extern crate env_logger;
//!
//! use log::LogLevel;
//! use log::Level;
//!
//! fn main() {
//! env_logger::init().unwrap();
@ -25,7 +25,7 @@
//! debug!("this is a debug {}", "message");
//! error!("this is printed by default");
//!
//! if log_enabled!(LogLevel::Info) {
//! if log_enabled!(Level::Info) {
//! let x = 3 * 4; // expensive computation
//! info!("the answer was: {}", x);
//! }
@ -80,7 +80,7 @@
//! form:
//!
//! ```text
//! path::to::module=log_level
//! path::to::module=level
//! ```
//!
//! The path to the module is rooted in the name of the crate it was compiled
@ -89,12 +89,12 @@
//! Furthermore, this path is a prefix-search, so all modules nested in the
//! specified module will also have logging enabled.
//!
//! The actual `log_level` is optional to specify. If omitted, all logging will
//! The actual `level` is optional to specify. If omitted, all logging will
//! be enabled. If specified, it must be one of the strings `debug`, `error`,
//! `info`, `warn`, or `trace`.
//!
//! As the log level for a module is optional, the module to enable logging for
//! is also optional. If only a `log_level` is provided, then the global log
//! is also optional. If only a `level` is provided, then the global log
//! level for all modules is set to this value.
//!
//! Some examples of valid values of `RUST_LOG` are:
@ -142,7 +142,7 @@ use std::io::prelude::*;
use std::io;
use std::mem;
use log::{Log, LogLevel, LogLevelFilter, LogRecord, SetLoggerError, LogMetadata};
use log::{Log, Level, LevelFilter, Record, SetLoggerError, Metadata};
#[cfg(feature = "regex")]
#[path = "regex.rs"]
@ -163,7 +163,7 @@ pub enum LogTarget {
pub struct Logger {
directives: Vec<LogDirective>,
filter: Option<filter::Filter>,
format: Box<Fn(&LogRecord) -> String + Sync + Send>,
format: Box<Fn(&Record) -> String + Sync + Send>,
target: LogTarget,
}
@ -179,16 +179,16 @@ pub struct Logger {
/// extern crate env_logger;
///
/// use std::env;
/// use log::{LogRecord, LogLevelFilter};
/// use log::{Record, LevelFilter};
/// use env_logger::LogBuilder;
///
/// fn main() {
/// let format = |record: &LogRecord| {
/// let format = |record: &Record| {
/// format!("{} - {}", record.level(), record.args())
/// };
///
/// let mut builder = LogBuilder::new();
/// builder.format(format).filter(None, LogLevelFilter::Info);
/// builder.format(format).filter(None, LevelFilter::Info);
///
/// if env::var("RUST_LOG").is_ok() {
/// builder.parse(&env::var("RUST_LOG").unwrap());
@ -203,7 +203,7 @@ pub struct Logger {
pub struct LogBuilder {
directives: Vec<LogDirective>,
filter: Option<filter::Filter>,
format: Box<Fn(&LogRecord) -> String + Sync + Send>,
format: Box<Fn(&Record) -> String + Sync + Send>,
target: LogTarget,
}
@ -213,7 +213,7 @@ impl LogBuilder {
LogBuilder {
directives: Vec::new(),
filter: None,
format: Box::new(|record: &LogRecord| {
format: Box::new(|record: &Record| {
format!("{}:{}: {}", record.level(),
record.location().module_path(), record.args())
}),
@ -227,7 +227,7 @@ impl LogBuilder {
/// If no module is provided then the filter will apply to all log messages.
pub fn filter(&mut self,
module: Option<&str>,
level: LogLevelFilter) -> &mut Self {
level: LevelFilter) -> &mut Self {
self.directives.push(LogDirective {
name: module.map(|s| s.to_string()),
level: level,
@ -240,7 +240,7 @@ impl LogBuilder {
/// This function is called on each record logged to produce a string which
/// is actually printed out.
pub fn format<F: 'static>(&mut self, format: F) -> &mut Self
where F: Fn(&LogRecord) -> String + Sync + Send
where F: Fn(&Record) -> String + Sync + Send
{
self.format = Box::new(format);
self
@ -288,7 +288,7 @@ impl LogBuilder {
// Adds the default filter if none exist
self.directives.push(LogDirective {
name: None,
level: LogLevelFilter::Error,
level: LevelFilter::Error,
});
} else {
// Sort the directives by length of their name, this allows a
@ -320,13 +320,13 @@ impl Logger {
builder.build()
}
pub fn filter(&self) -> LogLevelFilter {
pub fn filter(&self) -> LevelFilter {
self.directives.iter()
.map(|d| d.level).max()
.unwrap_or(LogLevelFilter::Off)
.unwrap_or(LevelFilter::Off)
}
fn enabled(&self, level: LogLevel, target: &str) -> bool {
fn enabled(&self, level: Level, target: &str) -> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in self.directives.iter().rev() {
match directive.name {
@ -341,11 +341,11 @@ impl Logger {
}
impl Log for Logger {
fn enabled(&self, metadata: &LogMetadata) -> bool {
fn enabled(&self, metadata: &Metadata) -> bool {
self.enabled(metadata.level(), metadata.target())
}
fn log(&self, record: &LogRecord) {
fn log(&self, record: &Record) {
if !Log::enabled(self, record.metadata()) {
return;
}
@ -367,7 +367,7 @@ impl Log for Logger {
struct LogDirective {
name: Option<String>,
level: LogLevelFilter,
level: LevelFilter,
}
/// Initializes the global logger with an env logger.
@ -407,10 +407,10 @@ fn parse_logging_spec(spec: &str) -> (Vec<LogDirective>, Option<filter::Filter>)
// treat that as a global fallback
match part0.parse() {
Ok(num) => (num, None),
Err(_) => (LogLevelFilter::max(), Some(part0)),
Err(_) => (LevelFilter::max(), Some(part0)),
}
}
(Some(part0), Some(""), None) => (LogLevelFilter::max(), Some(part0)),
(Some(part0), Some(""), None) => (LevelFilter::max(), Some(part0)),
(Some(part0), Some(part1), None) => {
match part1.parse() {
Ok(num) => (num, Some(part0)),
@ -448,7 +448,7 @@ fn parse_logging_spec(spec: &str) -> (Vec<LogDirective>, Option<filter::Filter>)
#[cfg(test)]
mod tests {
use log::{LogLevel, LogLevelFilter};
use log::{Level, LevelFilter};
use super::{LogBuilder, Logger, LogDirective, parse_logging_spec};
@ -460,27 +460,27 @@ mod tests {
#[test]
fn filter_info() {
let logger = LogBuilder::new().filter(None, LogLevelFilter::Info).build();
assert!(logger.enabled(LogLevel::Info, "crate1"));
assert!(!logger.enabled(LogLevel::Debug, "crate1"));
let logger = LogBuilder::new().filter(None, LevelFilter::Info).build();
assert!(logger.enabled(Level::Info, "crate1"));
assert!(!logger.enabled(Level::Debug, "crate1"));
}
#[test]
fn filter_beginning_longest_match() {
let logger = LogBuilder::new()
.filter(Some("crate2"), LogLevelFilter::Info)
.filter(Some("crate2::mod"), LogLevelFilter::Debug)
.filter(Some("crate1::mod1"), LogLevelFilter::Warn)
.filter(Some("crate2"), LevelFilter::Info)
.filter(Some("crate2::mod"), LevelFilter::Debug)
.filter(Some("crate1::mod1"), LevelFilter::Warn)
.build();
assert!(logger.enabled(LogLevel::Debug, "crate2::mod1"));
assert!(!logger.enabled(LogLevel::Debug, "crate2"));
assert!(logger.enabled(Level::Debug, "crate2::mod1"));
assert!(!logger.enabled(Level::Debug, "crate2"));
}
#[test]
fn parse_default() {
let logger = LogBuilder::new().parse("info,crate1::mod1=warn").build();
assert!(logger.enabled(LogLevel::Warn, "crate1::mod1"));
assert!(logger.enabled(LogLevel::Info, "crate2::mod2"));
assert!(logger.enabled(Level::Warn, "crate1::mod1"));
assert!(logger.enabled(Level::Info, "crate2::mod2"));
}
#[test]
@ -488,66 +488,66 @@ mod tests {
let logger = make_logger(vec![
LogDirective {
name: Some("crate2".to_string()),
level: LogLevelFilter::Info
level: LevelFilter::Info
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: LogLevelFilter::Warn
level: LevelFilter::Warn
}
]);
assert!(logger.enabled(LogLevel::Warn, "crate1::mod1"));
assert!(!logger.enabled(LogLevel::Info, "crate1::mod1"));
assert!(logger.enabled(LogLevel::Info, "crate2"));
assert!(!logger.enabled(LogLevel::Debug, "crate2"));
assert!(logger.enabled(Level::Warn, "crate1::mod1"));
assert!(!logger.enabled(Level::Info, "crate1::mod1"));
assert!(logger.enabled(Level::Info, "crate2"));
assert!(!logger.enabled(Level::Debug, "crate2"));
}
#[test]
fn no_match() {
let logger = make_logger(vec![
LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info },
LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn }
LogDirective { name: Some("crate2".to_string()), level: LevelFilter::Info },
LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
assert!(!logger.enabled(LogLevel::Warn, "crate3"));
assert!(!logger.enabled(Level::Warn, "crate3"));
}
#[test]
fn match_beginning() {
let logger = make_logger(vec![
LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info },
LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn }
LogDirective { name: Some("crate2".to_string()), level: LevelFilter::Info },
LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
assert!(logger.enabled(LogLevel::Info, "crate2::mod1"));
assert!(logger.enabled(Level::Info, "crate2::mod1"));
}
#[test]
fn match_beginning_longest_match() {
let logger = make_logger(vec![
LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info },
LogDirective { name: Some("crate2::mod".to_string()), level: LogLevelFilter::Debug },
LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn }
LogDirective { name: Some("crate2".to_string()), level: LevelFilter::Info },
LogDirective { name: Some("crate2::mod".to_string()), level: LevelFilter::Debug },
LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
assert!(logger.enabled(LogLevel::Debug, "crate2::mod1"));
assert!(!logger.enabled(LogLevel::Debug, "crate2"));
assert!(logger.enabled(Level::Debug, "crate2::mod1"));
assert!(!logger.enabled(Level::Debug, "crate2"));
}
#[test]
fn match_default() {
let logger = make_logger(vec![
LogDirective { name: None, level: LogLevelFilter::Info },
LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn }
LogDirective { name: None, level: LevelFilter::Info },
LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
assert!(logger.enabled(LogLevel::Warn, "crate1::mod1"));
assert!(logger.enabled(LogLevel::Info, "crate2::mod2"));
assert!(logger.enabled(Level::Warn, "crate1::mod1"));
assert!(logger.enabled(Level::Info, "crate2::mod2"));
}
#[test]
fn zero_level() {
let logger = make_logger(vec![
LogDirective { name: None, level: LogLevelFilter::Info },
LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Off }
LogDirective { name: None, level: LevelFilter::Info },
LogDirective { name: Some("crate1::mod1".to_string()), level: LevelFilter::Off }
]);
assert!(!logger.enabled(LogLevel::Error, "crate1::mod1"));
assert!(logger.enabled(LogLevel::Info, "crate2::mod2"));
assert!(!logger.enabled(Level::Error, "crate1::mod1"));
assert!(logger.enabled(Level::Info, "crate2::mod2"));
}
#[test]
@ -555,13 +555,13 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1::mod1=error,crate1::mod2,crate2=debug");
assert_eq!(dirs.len(), 3);
assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
assert_eq!(dirs[0].level, LogLevelFilter::Error);
assert_eq!(dirs[0].level, LevelFilter::Error);
assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
assert_eq!(dirs[1].level, LogLevelFilter::max());
assert_eq!(dirs[1].level, LevelFilter::max());
assert_eq!(dirs[2].name, Some("crate2".to_string()));
assert_eq!(dirs[2].level, LogLevelFilter::Debug);
assert_eq!(dirs[2].level, LevelFilter::Debug);
assert!(filter.is_none());
}
@ -571,37 +571,37 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1::mod1=warn=info,crate2=debug");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LogLevelFilter::Debug);
assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_none());
}
#[test]
fn parse_logging_spec_invalid_log_level() {
fn parse_logging_spec_invalid_level() {
// test parse_logging_spec with 'noNumber' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=noNumber,crate2=debug");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LogLevelFilter::Debug);
assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_none());
}
#[test]
fn parse_logging_spec_string_log_level() {
fn parse_logging_spec_string_level() {
// test parse_logging_spec with 'warn' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=warn");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LogLevelFilter::Warn);
assert_eq!(dirs[0].level, LevelFilter::Warn);
assert!(filter.is_none());
}
#[test]
fn parse_logging_spec_empty_log_level() {
fn parse_logging_spec_empty_level() {
// test parse_logging_spec with '' as log level
let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LogLevelFilter::max());
assert_eq!(dirs[0].level, LevelFilter::max());
assert!(filter.is_none());
}
@ -611,9 +611,9 @@ mod tests {
let (dirs, filter) = parse_logging_spec("warn,crate2=debug");
assert_eq!(dirs.len(), 2);
assert_eq!(dirs[0].name, None);
assert_eq!(dirs[0].level, LogLevelFilter::Warn);
assert_eq!(dirs[0].level, LevelFilter::Warn);
assert_eq!(dirs[1].name, Some("crate2".to_string()));
assert_eq!(dirs[1].level, LogLevelFilter::Debug);
assert_eq!(dirs[1].level, LevelFilter::Debug);
assert!(filter.is_none());
}
@ -622,13 +622,13 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1::mod1=error,crate1::mod2,crate2=debug/abc");
assert_eq!(dirs.len(), 3);
assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
assert_eq!(dirs[0].level, LogLevelFilter::Error);
assert_eq!(dirs[0].level, LevelFilter::Error);
assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
assert_eq!(dirs[1].level, LogLevelFilter::max());
assert_eq!(dirs[1].level, LevelFilter::max());
assert_eq!(dirs[2].name, Some("crate2".to_string()));
assert_eq!(dirs[2].level, LogLevelFilter::Debug);
assert_eq!(dirs[2].level, LevelFilter::Debug);
assert!(filter.is_some() && filter.unwrap().to_string() == "abc");
}
@ -637,7 +637,7 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1::mod1=error=warn,crate2=debug/a.c");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LogLevelFilter::Debug);
assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_some() && filter.unwrap().to_string() == "a.c");
}
@ -646,7 +646,7 @@ mod tests {
let (dirs, filter) = parse_logging_spec("crate1/a*c");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate1".to_string()));
assert_eq!(dirs[0].level, LogLevelFilter::max());
assert_eq!(dirs[0].level, LevelFilter::max());
assert!(filter.is_some() && filter.unwrap().to_string() == "a*c");
}
}

View File

@ -101,16 +101,16 @@
//! ```rust
//! extern crate log;
//!
//! use log::{LogRecord, LogLevel, LogMetadata};
//! use log::{Record, Level, Metadata};
//!
//! struct SimpleLogger;
//!
//! impl log::Log for SimpleLogger {
//! fn enabled(&self, metadata: &LogMetadata) -> bool {
//! metadata.level() <= LogLevel::Info
//! fn enabled(&self, metadata: &Metadata) -> bool {
//! metadata.level() <= Level::Info
//! }
//!
//! fn log(&self, record: &LogRecord) {
//! fn log(&self, record: &Record) {
//! if self.enabled(record.metadata()) {
//! println!("{} - {}", record.level(), record.args());
//! }
@ -121,8 +121,8 @@
//! ```
//!
//! Loggers are installed by calling the [`set_logger`] function. It takes a
//! closure which is provided a [`MaxLogLevelFilter`] token and returns a
//! [`Log`] trait object. The [`MaxLogLevelFilter`] token controls the global
//! closure which is provided a [`MaxLevelFilter`] token and returns a
//! [`Log`] trait object. The [`MaxLevelFilter`] token controls the global
//! maximum log level. The logging facade uses this as an optimization to
//! improve performance of log messages at levels that are disabled. In the
//! case of our example logger, we'll want to set the maximum log level to
@ -133,17 +133,17 @@
//!
//! ```rust
//! # extern crate log;
//! # use log::{LogLevel, LogLevelFilter, SetLoggerError, LogMetadata};
//! # use log::{Level, LevelFilter, SetLoggerError, Metadata};
//! # struct SimpleLogger;
//! # impl log::Log for SimpleLogger {
//! # fn enabled(&self, _: &LogMetadata) -> bool { false }
//! # fn log(&self, _: &log::LogRecord) {}
//! # fn enabled(&self, _: &Metadata) -> bool { false }
//! # fn log(&self, _: &log::Record) {}
//! # }
//! # fn main() {}
//! # #[cfg(feature = "use_std")]
//! pub fn init() -> Result<(), SetLoggerError> {
//! log::set_logger(|max_log_level| {
//! max_log_level.set(LogLevelFilter::Info);
//! log::set_logger(|max_level| {
//! max_level.set(LevelFilter::Info);
//! Box::new(SimpleLogger)
//! })
//! }
@ -160,12 +160,12 @@
//!
//! ```rust
//! # extern crate log;
//! # use log::{LogLevel, LogLevelFilter, SetLoggerError, ShutdownLoggerError,
//! # LogMetadata};
//! # use log::{Level, LevelFilter, SetLoggerError, ShutdownLoggerError,
//! # Metadata};
//! # struct SimpleLogger;
//! # impl log::Log for SimpleLogger {
//! # fn enabled(&self, _: &LogMetadata) -> bool { false }
//! # fn log(&self, _: &log::LogRecord) {}
//! # fn enabled(&self, _: &Metadata) -> bool { false }
//! # fn log(&self, _: &log::Record) {}
//! # }
//! # impl SimpleLogger {
//! # fn flush(&self) {}
@ -173,9 +173,9 @@
//! # fn main() {}
//! pub fn init() -> Result<(), SetLoggerError> {
//! unsafe {
//! log::set_logger_raw(|max_log_level| {
//! log::set_logger_raw(|max_level| {
//! static LOGGER: SimpleLogger = SimpleLogger;
//! max_log_level.set(LogLevelFilter::Info);
//! max_level.set(LevelFilter::Info);
//! &SimpleLogger
//! })
//! }
@ -189,9 +189,9 @@
//! ```
//!
//! [`Log`]: trait.Log.html
//! [level_link]: enum.LogLevel.html
//! [level_link]: enum.Level.html
//! [`set_logger`]: fn.set_logger.html
//! [`MaxLogLevelFilter`]: struct.MaxLogLevelFilter.html
//! [`MaxLevelFilter`]: struct.MaxLevelFilter.html
//! [`set_logger_raw`]: fn.set_logger_raw.html
//! [`shutdown_logger_raw`]: fn.shutdown_logger_raw.html
@ -258,17 +258,17 @@ static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO",
/// An enum representing the available verbosity levels of the logging framework.
///
/// Typical usage includes: checking if a certain `LogLevel` is enabled with
/// [`log_enabled!`](macro.log_enabled.html), specifying the `LogLevel` of
/// [`log!`](macro.log.html), and comparing a `LogLevel` directly to a
/// [`LogLevelFilter`](enum.LogLevelFilter.html).
/// Typical usage includes: checking if a certain `Level` is enabled with
/// [`log_enabled!`](macro.log_enabled.html), specifying the `Level` of
/// [`log!`](macro.log.html), and comparing a `Level` directly to a
/// [`LevelFilter`](enum.LevelFilter.html).
#[repr(usize)]
#[derive(Copy, Eq, Debug, Hash)]
pub enum LogLevel {
pub enum Level {
/// The "error" level.
///
/// Designates very serious errors.
Error = 1, // This way these line up with the discriminants for LogLevelFilter below
Error = 1, // This way these line up with the discriminants for LevelFilter below
/// The "warn" level.
///
/// Designates hazardous situations.
@ -287,44 +287,44 @@ pub enum LogLevel {
Trace,
}
impl Clone for LogLevel {
impl Clone for Level {
#[inline]
fn clone(&self) -> LogLevel {
fn clone(&self) -> Level {
*self
}
}
impl PartialEq for LogLevel {
impl PartialEq for Level {
#[inline]
fn eq(&self, other: &LogLevel) -> bool {
fn eq(&self, other: &Level) -> bool {
*self as usize == *other as usize
}
}
impl PartialEq<LogLevelFilter> for LogLevel {
impl PartialEq<LevelFilter> for Level {
#[inline]
fn eq(&self, other: &LogLevelFilter) -> bool {
fn eq(&self, other: &LevelFilter) -> bool {
*self as usize == *other as usize
}
}
impl PartialOrd for LogLevel {
impl PartialOrd for Level {
#[inline]
fn partial_cmp(&self, other: &LogLevel) -> Option<cmp::Ordering> {
fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialOrd<LogLevelFilter> for LogLevel {
impl PartialOrd<LevelFilter> for Level {
#[inline]
fn partial_cmp(&self, other: &LogLevelFilter) -> Option<cmp::Ordering> {
fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
Some((*self as usize).cmp(&(*other as usize)))
}
}
impl Ord for LogLevel {
impl Ord for Level {
#[inline]
fn cmp(&self, other: &LogLevel) -> cmp::Ordering {
fn cmp(&self, other: &Level) -> cmp::Ordering {
(*self as usize).cmp(&(*other as usize))
}
}
@ -355,60 +355,60 @@ fn eq_ignore_ascii_case(a: &str, b: &str) -> bool {
}
}
impl FromStr for LogLevel {
impl FromStr for Level {
type Err = ();
fn from_str(level: &str) -> Result<LogLevel, ()> {
fn from_str(level: &str) -> Result<Level, ()> {
ok_or(LOG_LEVEL_NAMES.iter()
.position(|&name| eq_ignore_ascii_case(name, level))
.into_iter()
.filter(|&idx| idx != 0)
.map(|idx| LogLevel::from_usize(idx).unwrap())
.map(|idx| Level::from_usize(idx).unwrap())
.next(), ())
}
}
impl fmt::Display for LogLevel {
impl fmt::Display for Level {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad(LOG_LEVEL_NAMES[*self as usize])
}
}
impl LogLevel {
fn from_usize(u: usize) -> Option<LogLevel> {
impl Level {
fn from_usize(u: usize) -> Option<Level> {
match u {
1 => Some(LogLevel::Error),
2 => Some(LogLevel::Warn),
3 => Some(LogLevel::Info),
4 => Some(LogLevel::Debug),
5 => Some(LogLevel::Trace),
1 => Some(Level::Error),
2 => Some(Level::Warn),
3 => Some(Level::Info),
4 => Some(Level::Debug),
5 => Some(Level::Trace),
_ => None
}
}
/// Returns the most verbose logging level.
#[inline]
pub fn max() -> LogLevel {
LogLevel::Trace
pub fn max() -> Level {
Level::Trace
}
/// Converts the `LogLevel` to the equivalent `LogLevelFilter`.
/// Converts the `Level` to the equivalent `LevelFilter`.
#[inline]
pub fn to_log_level_filter(&self) -> LogLevelFilter {
LogLevelFilter::from_usize(*self as usize).unwrap()
pub fn to_level_filter(&self) -> LevelFilter {
LevelFilter::from_usize(*self as usize).unwrap()
}
}
/// An enum representing the available verbosity level filters of the logging
/// framework.
///
/// A `LogLevelFilter` may be compared directly to a [`LogLevel`](enum.LogLevel.html).
/// Use this type to [`get()`](struct.MaxLogLevelFilter.html#method.get) and
/// [`set()`](struct.MaxLogLevelFilter.html#method.set) the
/// [`MaxLogLevelFilter`](struct.MaxLogLevelFilter.html), or to match with the getter
/// [`max_log_level()`](fn.max_log_level.html).
/// A `LevelFilter` may be compared directly to a [`Level`](enum.Level.html).
/// Use this type to [`get()`](struct.MaxLevelFilter.html#method.get) and
/// [`set()`](struct.MaxLevelFilter.html#method.set) the
/// [`MaxLevelFilter`](struct.MaxLevelFilter.html), or to match with the getter
/// [`max_level()`](fn.max_level.html).
#[repr(usize)]
#[derive(Copy, Eq, Debug, Hash)]
pub enum LogLevelFilter {
pub enum LevelFilter {
/// A level lower than all log levels.
Off,
/// Corresponds to the `Error` log level.
@ -425,87 +425,87 @@ pub enum LogLevelFilter {
// Deriving generates terrible impls of these traits
impl Clone for LogLevelFilter {
impl Clone for LevelFilter {
#[inline]
fn clone(&self) -> LogLevelFilter {
fn clone(&self) -> LevelFilter {
*self
}
}
impl PartialEq for LogLevelFilter {
impl PartialEq for LevelFilter {
#[inline]
fn eq(&self, other: &LogLevelFilter) -> bool {
fn eq(&self, other: &LevelFilter) -> bool {
*self as usize == *other as usize
}
}
impl PartialEq<LogLevel> for LogLevelFilter {
impl PartialEq<Level> for LevelFilter {
#[inline]
fn eq(&self, other: &LogLevel) -> bool {
fn eq(&self, other: &Level) -> bool {
other.eq(self)
}
}
impl PartialOrd for LogLevelFilter {
impl PartialOrd for LevelFilter {
#[inline]
fn partial_cmp(&self, other: &LogLevelFilter) -> Option<cmp::Ordering> {
fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialOrd<LogLevel> for LogLevelFilter {
impl PartialOrd<Level> for LevelFilter {
#[inline]
fn partial_cmp(&self, other: &LogLevel) -> Option<cmp::Ordering> {
fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
other.partial_cmp(self).map(|x| x.reverse())
}
}
impl Ord for LogLevelFilter {
impl Ord for LevelFilter {
#[inline]
fn cmp(&self, other: &LogLevelFilter) -> cmp::Ordering {
fn cmp(&self, other: &LevelFilter) -> cmp::Ordering {
(*self as usize).cmp(&(*other as usize))
}
}
impl FromStr for LogLevelFilter {
impl FromStr for LevelFilter {
type Err = ();
fn from_str(level: &str) -> Result<LogLevelFilter, ()> {
fn from_str(level: &str) -> Result<LevelFilter, ()> {
ok_or(LOG_LEVEL_NAMES.iter()
.position(|&name| eq_ignore_ascii_case(name, level))
.map(|p| LogLevelFilter::from_usize(p).unwrap()), ())
.map(|p| LevelFilter::from_usize(p).unwrap()), ())
}
}
impl fmt::Display for LogLevelFilter {
impl fmt::Display for LevelFilter {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", LOG_LEVEL_NAMES[*self as usize])
}
}
impl LogLevelFilter {
fn from_usize(u: usize) -> Option<LogLevelFilter> {
impl LevelFilter {
fn from_usize(u: usize) -> Option<LevelFilter> {
match u {
0 => Some(LogLevelFilter::Off),
1 => Some(LogLevelFilter::Error),
2 => Some(LogLevelFilter::Warn),
3 => Some(LogLevelFilter::Info),
4 => Some(LogLevelFilter::Debug),
5 => Some(LogLevelFilter::Trace),
0 => Some(LevelFilter::Off),
1 => Some(LevelFilter::Error),
2 => Some(LevelFilter::Warn),
3 => Some(LevelFilter::Info),
4 => Some(LevelFilter::Debug),
5 => Some(LevelFilter::Trace),
_ => None
}
}
/// Returns the most verbose logging level filter.
#[inline]
pub fn max() -> LogLevelFilter {
LogLevelFilter::Trace
pub fn max() -> LevelFilter {
LevelFilter::Trace
}
/// Converts `self` to the equivalent `LogLevel`.
/// Converts `self` to the equivalent `Level`.
///
/// Returns `None` if `self` is `LogLevelFilter::Off`.
/// Returns `None` if `self` is `LevelFilter::Off`.
#[inline]
pub fn to_log_level(&self) -> Option<LogLevel> {
LogLevel::from_usize(*self as usize)
pub fn to_level(&self) -> Option<Level> {
Level::from_usize(*self as usize)
}
}
@ -515,30 +515,30 @@ impl LogLevelFilter {
/// [`log`]: trait.Log.html#tymethod.log
/// [`Log`]: trait.Log.html
#[derive(Debug)]
pub struct LogRecord<'a> {
metadata: LogMetadata<'a>,
location: &'a LogLocation,
pub struct Record<'a> {
metadata: Metadata<'a>,
location: &'a Location,
args: fmt::Arguments<'a>,
}
impl<'a> LogRecord<'a> {
impl<'a> Record<'a> {
/// The message body.
pub fn args(&self) -> &fmt::Arguments<'a> {
&self.args
}
/// Metadata about the log directive.
pub fn metadata(&self) -> &LogMetadata {
pub fn metadata(&self) -> &Metadata {
&self.metadata
}
/// The location of the log directive.
pub fn location(&self) -> &LogLocation {
pub fn location(&self) -> &Location {
self.location
}
/// The verbosity level of the message.
pub fn level(&self) -> LogLevel {
pub fn level(&self) -> Level {
self.metadata.level()
}
@ -550,14 +550,14 @@ impl<'a> LogRecord<'a> {
/// Metadata about a log message.
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct LogMetadata<'a> {
level: LogLevel,
pub struct Metadata<'a> {
level: Level,
target: &'a str,
}
impl<'a> LogMetadata<'a> {
impl<'a> Metadata<'a> {
/// The verbosity level of the message.
pub fn level(&self) -> LogLevel {
pub fn level(&self) -> Level {
self.level
}
@ -575,23 +575,23 @@ pub trait Log: Sync+Send {
/// This is used by the `log_enabled!` macro to allow callers to avoid
/// expensive computation of log message arguments if the message would be
/// discarded anyway.
fn enabled(&self, metadata: &LogMetadata) -> bool;
fn enabled(&self, metadata: &Metadata) -> bool;
/// Logs the `LogRecord`.
/// Logs the `Record`.
///
/// Note that `enabled` is *not* necessarily called before this method.
/// Implementations of `log` should perform all necessary filtering
/// internally.
fn log(&self, record: &LogRecord);
fn log(&self, record: &Record);
}
// Just used as a dummy initial value for LOGGER
struct NopLogger;
impl Log for NopLogger {
fn enabled(&self, _: &LogMetadata) -> bool { false }
fn enabled(&self, _: &Metadata) -> bool { false }
fn log(&self, _: &LogRecord) {}
fn log(&self, _: &Record) {}
}
/// The location of a log message.
@ -602,7 +602,7 @@ impl Log for NopLogger {
/// `log!` macro. They are subject to change at any time and should never be
/// accessed directly.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct LogLocation {
pub struct Location {
#[doc(hidden)]
pub __module_path: &'static str,
#[doc(hidden)]
@ -611,7 +611,7 @@ pub struct LogLocation {
pub __line: u32,
}
impl LogLocation {
impl Location {
/// The module path of the message.
pub fn module_path(&self) -> &str {
self.__module_path
@ -637,22 +637,22 @@ impl LogLocation {
/// make sure to keep the maximum log level filter in sync with its current
/// configuration.
#[allow(missing_copy_implementations)]
pub struct MaxLogLevelFilter(());
pub struct MaxLevelFilter(());
impl fmt::Debug for MaxLogLevelFilter {
impl fmt::Debug for MaxLevelFilter {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "MaxLogLevelFilter")
write!(fmt, "MaxLevelFilter")
}
}
impl MaxLogLevelFilter {
impl MaxLevelFilter {
/// Gets the current maximum log level filter.
pub fn get(&self) -> LogLevelFilter {
max_log_level()
pub fn get(&self) -> LevelFilter {
max_level()
}
/// Sets the maximum log level.
pub fn set(&self, level: LogLevelFilter) {
pub fn set(&self, level: LevelFilter) {
MAX_LOG_LEVEL_FILTER.store(level as usize, Ordering::SeqCst)
}
}
@ -661,15 +661,15 @@ impl MaxLogLevelFilter {
///
/// The `log!`, `error!`, `warn!`, `info!`, `debug!`, and `trace!` macros check
/// this value and discard any message logged at a higher level. The maximum
/// log level is set by the `MaxLogLevel` token passed to loggers.
/// log level is set by the `MaxLevel` token passed to loggers.
#[inline(always)]
pub fn max_log_level() -> LogLevelFilter {
pub fn max_level() -> LevelFilter {
unsafe { mem::transmute(MAX_LOG_LEVEL_FILTER.load(Ordering::Relaxed)) }
}
/// Sets the global logger.
///
/// The `make_logger` closure is passed a `MaxLogLevel` object, which the
/// The `make_logger` closure is passed a `MaxLevel` object, which the
/// logger should use to keep the global maximum log level in sync with the
/// highest log level that the logger will not ignore.
///
@ -684,7 +684,7 @@ pub fn max_log_level() -> LogLevelFilter {
/// Requires the `use_std` feature (enabled by default).
#[cfg(feature = "use_std")]
pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
where M: FnOnce(MaxLevelFilter) -> Box<Log> {
unsafe { set_logger_raw(|max_level| mem::transmute(make_logger(max_level))) }
}
@ -693,7 +693,7 @@ pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
/// This function is similar to `set_logger` except that it is usable in
/// `no_std` code.
///
/// The `make_logger` closure is passed a `MaxLogLevel` object, which the
/// The `make_logger` closure is passed a `MaxLevel` object, which the
/// logger should use to keep the global maximum log level in sync with the
/// highest log level that the logger will not ignore.
///
@ -711,13 +711,13 @@ pub fn set_logger<M>(make_logger: M) -> Result<(), SetLoggerError>
/// duration of the program or until `shutdown_logger_raw` is called. In
/// addition, `shutdown_logger` *must not* be called after this function.
pub unsafe fn set_logger_raw<M>(make_logger: M) -> Result<(), SetLoggerError>
where M: FnOnce(MaxLogLevelFilter) -> *const Log {
where M: FnOnce(MaxLevelFilter) -> *const Log {
if STATE.compare_and_swap(UNINITIALIZED, INITIALIZING,
Ordering::SeqCst) != UNINITIALIZED {
return Err(SetLoggerError(()));
}
LOGGER = make_logger(MaxLogLevelFilter(()));
LOGGER = make_logger(MaxLevelFilter(()));
STATE.store(INITIALIZED, Ordering::SeqCst);
Ok(())
}
@ -877,9 +877,9 @@ fn logger() -> Option<LoggerGuard> {
// This is not considered part of the crate's public API. It is subject to
// change at any time.
#[doc(hidden)]
pub fn __enabled(level: LogLevel, target: &str) -> bool {
pub fn __enabled(level: Level, target: &str) -> bool {
if let Some(logger) = logger() {
logger.enabled(&LogMetadata { level: level, target: target })
logger.enabled(&Metadata { level: level, target: target })
} else {
false
}
@ -889,11 +889,11 @@ pub fn __enabled(level: LogLevel, target: &str) -> bool {
// This is not considered part of the crate's public API. It is subject to
// change at any time.
#[doc(hidden)]
pub fn __log(level: LogLevel, target: &str, loc: &LogLocation,
pub fn __log(level: Level, target: &str, loc: &Location,
args: fmt::Arguments) {
if let Some(logger) = logger() {
let record = LogRecord {
metadata: LogMetadata {
let record = Record {
metadata: Metadata {
level: level,
target: target,
},
@ -909,35 +909,35 @@ pub fn __log(level: LogLevel, target: &str, loc: &LogLocation,
// change at any time.
#[inline(always)]
#[doc(hidden)]
pub fn __static_max_level() -> LogLevelFilter {
pub fn __static_max_level() -> LevelFilter {
if !cfg!(debug_assertions) {
// This is a release build. Check `release_max_level_*` first.
if cfg!(feature = "release_max_level_off") {
return LogLevelFilter::Off
return LevelFilter::Off
} else if cfg!(feature = "release_max_level_error") {
return LogLevelFilter::Error
return LevelFilter::Error
} else if cfg!(feature = "release_max_level_warn") {
return LogLevelFilter::Warn
return LevelFilter::Warn
} else if cfg!(feature = "release_max_level_info") {
return LogLevelFilter::Info
return LevelFilter::Info
} else if cfg!(feature = "release_max_level_debug") {
return LogLevelFilter::Debug
return LevelFilter::Debug
} else if cfg!(feature = "release_max_level_trace") {
return LogLevelFilter::Trace
return LevelFilter::Trace
}
}
if cfg!(feature = "max_level_off") {
LogLevelFilter::Off
LevelFilter::Off
} else if cfg!(feature = "max_level_error") {
LogLevelFilter::Error
LevelFilter::Error
} else if cfg!(feature = "max_level_warn") {
LogLevelFilter::Warn
LevelFilter::Warn
} else if cfg!(feature = "max_level_info") {
LogLevelFilter::Info
LevelFilter::Info
} else if cfg!(feature = "max_level_debug") {
LogLevelFilter::Debug
LevelFilter::Debug
} else {
LogLevelFilter::Trace
LevelFilter::Trace
}
}
@ -945,23 +945,23 @@ pub fn __static_max_level() -> LogLevelFilter {
mod tests {
extern crate std;
use tests::std::string::ToString;
use super::{LogLevel, LogLevelFilter};
use super::{Level, LevelFilter};
#[test]
fn test_loglevelfilter_from_str() {
fn test_levelfilter_from_str() {
let tests = [
("off", Ok(LogLevelFilter::Off)),
("error", Ok(LogLevelFilter::Error)),
("warn", Ok(LogLevelFilter::Warn)),
("info", Ok(LogLevelFilter::Info)),
("debug", Ok(LogLevelFilter::Debug)),
("trace", Ok(LogLevelFilter::Trace)),
("OFF", Ok(LogLevelFilter::Off)),
("ERROR", Ok(LogLevelFilter::Error)),
("WARN", Ok(LogLevelFilter::Warn)),
("INFO", Ok(LogLevelFilter::Info)),
("DEBUG", Ok(LogLevelFilter::Debug)),
("TRACE", Ok(LogLevelFilter::Trace)),
("off", Ok(LevelFilter::Off)),
("error", Ok(LevelFilter::Error)),
("warn", Ok(LevelFilter::Warn)),
("info", Ok(LevelFilter::Info)),
("debug", Ok(LevelFilter::Debug)),
("trace", Ok(LevelFilter::Trace)),
("OFF", Ok(LevelFilter::Off)),
("ERROR", Ok(LevelFilter::Error)),
("WARN", Ok(LevelFilter::Warn)),
("INFO", Ok(LevelFilter::Info)),
("DEBUG", Ok(LevelFilter::Debug)),
("TRACE", Ok(LevelFilter::Trace)),
("asdf", Err(())),
];
for &(s, ref expected) in &tests {
@ -970,19 +970,19 @@ mod tests {
}
#[test]
fn test_loglevel_from_str() {
fn test_level_from_str() {
let tests = [
("OFF", Err(())),
("error", Ok(LogLevel::Error)),
("warn", Ok(LogLevel::Warn)),
("info", Ok(LogLevel::Info)),
("debug", Ok(LogLevel::Debug)),
("trace", Ok(LogLevel::Trace)),
("ERROR", Ok(LogLevel::Error)),
("WARN", Ok(LogLevel::Warn)),
("INFO", Ok(LogLevel::Info)),
("DEBUG", Ok(LogLevel::Debug)),
("TRACE", Ok(LogLevel::Trace)),
("error", Ok(Level::Error)),
("warn", Ok(Level::Warn)),
("info", Ok(Level::Info)),
("debug", Ok(Level::Debug)),
("trace", Ok(Level::Trace)),
("ERROR", Ok(Level::Error)),
("WARN", Ok(Level::Warn)),
("INFO", Ok(Level::Info)),
("DEBUG", Ok(Level::Debug)),
("TRACE", Ok(Level::Trace)),
("asdf", Err(())),
];
for &(s, ref expected) in &tests {
@ -991,42 +991,42 @@ mod tests {
}
#[test]
fn test_loglevel_show() {
assert_eq!("INFO", LogLevel::Info.to_string());
assert_eq!("ERROR", LogLevel::Error.to_string());
fn test_level_show() {
assert_eq!("INFO", Level::Info.to_string());
assert_eq!("ERROR", Level::Error.to_string());
}
#[test]
fn test_loglevelfilter_show() {
assert_eq!("OFF", LogLevelFilter::Off.to_string());
assert_eq!("ERROR", LogLevelFilter::Error.to_string());
fn test_levelfilter_show() {
assert_eq!("OFF", LevelFilter::Off.to_string());
assert_eq!("ERROR", LevelFilter::Error.to_string());
}
#[test]
fn test_cross_cmp() {
assert!(LogLevel::Debug > LogLevelFilter::Error);
assert!(LogLevelFilter::Warn < LogLevel::Trace);
assert!(LogLevelFilter::Off < LogLevel::Error);
assert!(Level::Debug > LevelFilter::Error);
assert!(LevelFilter::Warn < Level::Trace);
assert!(LevelFilter::Off < Level::Error);
}
#[test]
fn test_cross_eq() {
assert!(LogLevel::Error == LogLevelFilter::Error);
assert!(LogLevelFilter::Off != LogLevel::Error);
assert!(LogLevel::Trace == LogLevelFilter::Trace);
assert!(Level::Error == LevelFilter::Error);
assert!(LevelFilter::Off != Level::Error);
assert!(Level::Trace == LevelFilter::Trace);
}
#[test]
fn test_to_log_level() {
assert_eq!(Some(LogLevel::Error), LogLevelFilter::Error.to_log_level());
assert_eq!(None, LogLevelFilter::Off.to_log_level());
assert_eq!(Some(LogLevel::Debug), LogLevelFilter::Debug.to_log_level());
fn test_to_level() {
assert_eq!(Some(Level::Error), LevelFilter::Error.to_level());
assert_eq!(None, LevelFilter::Off.to_level());
assert_eq!(Some(Level::Debug), LevelFilter::Debug.to_level());
}
#[test]
fn test_to_log_level_filter() {
assert_eq!(LogLevelFilter::Error, LogLevel::Error.to_log_level_filter());
assert_eq!(LogLevelFilter::Trace, LogLevel::Trace.to_log_level_filter());
fn test_to_level_filter() {
assert_eq!(LevelFilter::Error, Level::Error.to_level_filter());
assert_eq!(LevelFilter::Trace, Level::Trace.to_level_filter());
}
#[test]

View File

@ -9,7 +9,7 @@
// except according to those terms.
/// The standard logging macro.
///
/// This macro will generically log with the specified `LogLevel` and `format!`
/// This macro will generically log with the specified `Level` and `format!`
/// based argument list.
///
/// The `max_level_*` features can be used to statically disable logging at
@ -20,27 +20,27 @@
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// use log::LogLevel;
/// use log::Level;
///
/// # fn main() {
/// let data = (42, "Forty-two");
/// let private_data = "private";
///
/// log!(LogLevel::Error, "Received errors: {}, {}", data.0, data.1);
/// log!(target: "app_events", LogLevel::Warn, "App warning: {}, {}, {}",
/// log!(Level::Error, "Received errors: {}, {}", data.0, data.1);
/// log!(target: "app_events", Level::Warn, "App warning: {}, {}, {}",
/// data.0, data.1, private_data);
/// # }
/// ```
#[macro_export]
macro_rules! log {
(target: $target:expr, $lvl:expr, $($arg:tt)+) => ({
static _LOC: $crate::LogLocation = $crate::LogLocation {
static _LOC: $crate::Location = $crate::Location {
__line: line!(),
__file: file!(),
__module_path: module_path!(),
};
let lvl = $lvl;
if lvl <= $crate::__static_max_level() && lvl <= $crate::max_log_level() {
if lvl <= $crate::__static_max_level() && lvl <= $crate::max_level() {
$crate::__log(lvl, $target, &_LOC, format_args!($($arg)+))
}
});
@ -66,10 +66,10 @@ macro_rules! log {
#[macro_export]
macro_rules! error {
(target: $target:expr, $($arg:tt)*) => (
log!(target: $target, $crate::LogLevel::Error, $($arg)*);
log!(target: $target, $crate::Level::Error, $($arg)*);
);
($($arg:tt)*) => (
log!($crate::LogLevel::Error, $($arg)*);
log!($crate::Level::Error, $($arg)*);
)
}
@ -97,10 +97,10 @@ macro_rules! error {
#[macro_export]
macro_rules! warn {
(target: $target:expr, $($arg:tt)*) => (
log!(target: $target, $crate::LogLevel::Warn, $($arg)*);
log!(target: $target, $crate::Level::Warn, $($arg)*);
);
($($arg:tt)*) => (
log!($crate::LogLevel::Warn, $($arg)*);
log!($crate::Level::Warn, $($arg)*);
)
}
@ -131,10 +131,10 @@ macro_rules! warn {
#[macro_export]
macro_rules! info {
(target: $target:expr, $($arg:tt)*) => (
log!(target: $target, $crate::LogLevel::Info, $($arg)*);
log!(target: $target, $crate::Level::Info, $($arg)*);
);
($($arg:tt)*) => (
log!($crate::LogLevel::Info, $($arg)*);
log!($crate::Level::Info, $($arg)*);
)
}
@ -165,10 +165,10 @@ macro_rules! info {
#[macro_export]
macro_rules! debug {
(target: $target:expr, $($arg:tt)*) => (
log!(target: $target, $crate::LogLevel::Debug, $($arg)*);
log!(target: $target, $crate::Level::Debug, $($arg)*);
);
($($arg:tt)*) => (
log!($crate::LogLevel::Debug, $($arg)*);
log!($crate::Level::Debug, $($arg)*);
)
}
@ -202,10 +202,10 @@ macro_rules! debug {
#[macro_export]
macro_rules! trace {
(target: $target:expr, $($arg:tt)*) => (
log!(target: $target, $crate::LogLevel::Trace, $($arg)*);
log!(target: $target, $crate::Level::Trace, $($arg)*);
);
($($arg:tt)*) => (
log!($crate::LogLevel::Trace, $($arg)*);
log!($crate::Level::Trace, $($arg)*);
)
}
@ -220,7 +220,7 @@ macro_rules! trace {
/// ```rust
/// # #[macro_use]
/// # extern crate log;
/// use log::LogLevel::Debug;
/// use log::Level::Debug;
///
/// # fn foo() {
/// if log_enabled!(Debug) {
@ -236,7 +236,7 @@ macro_rules! trace {
macro_rules! log_enabled {
(target: $target:expr, $lvl:expr) => ({
let lvl = $lvl;
lvl <= $crate::__static_max_level() && lvl <= $crate::max_log_level() &&
lvl <= $crate::__static_max_level() && lvl <= $crate::max_level() &&
$crate::__enabled(lvl, $target)
});
($lvl:expr) => (log_enabled!(target: module_path!(), $lvl))

View File

@ -1,32 +1,32 @@
#[macro_use] extern crate log;
use std::sync::{Arc, Mutex};
use log::{LogLevel, LogLevelFilter, Log, LogRecord, LogMetadata};
use log::MaxLogLevelFilter;
use log::{Level, LevelFilter, Log, Record, Metadata};
use log::MaxLevelFilter;
#[cfg(feature = "use_std")]
use log::set_logger;
#[cfg(not(feature = "use_std"))]
fn set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
where M: FnOnce(MaxLevelFilter) -> Box<Log> {
unsafe {
log::set_logger_raw(|x| std::mem::transmute(make_logger(x)))
}
}
struct State {
last_log: Mutex<Option<LogLevel>>,
filter: MaxLogLevelFilter,
last_log: Mutex<Option<Level>>,
filter: MaxLevelFilter,
}
struct Logger(Arc<State>);
impl Log for Logger {
fn enabled(&self, _: &LogMetadata) -> bool {
fn enabled(&self, _: &Metadata) -> bool {
true
}
fn log(&self, record: &LogRecord) {
fn log(&self, record: &Record) {
*self.0.last_log.lock().unwrap() = Some(record.level());
}
}
@ -43,33 +43,33 @@ fn main() {
}).unwrap();
let a = a.unwrap();
test(&a, LogLevelFilter::Off);
test(&a, LogLevelFilter::Error);
test(&a, LogLevelFilter::Warn);
test(&a, LogLevelFilter::Info);
test(&a, LogLevelFilter::Debug);
test(&a, LogLevelFilter::Trace);
test(&a, LevelFilter::Off);
test(&a, LevelFilter::Error);
test(&a, LevelFilter::Warn);
test(&a, LevelFilter::Info);
test(&a, LevelFilter::Debug);
test(&a, LevelFilter::Trace);
}
fn test(a: &State, filter: LogLevelFilter) {
fn test(a: &State, filter: LevelFilter) {
a.filter.set(filter);
error!("");
last(&a, t(LogLevel::Error, filter));
last(&a, t(Level::Error, filter));
warn!("");
last(&a, t(LogLevel::Warn, filter));
last(&a, t(Level::Warn, filter));
info!("");
last(&a, t(LogLevel::Info, filter));
last(&a, t(Level::Info, filter));
debug!("");
last(&a, t(LogLevel::Debug, filter));
last(&a, t(Level::Debug, filter));
trace!("");
last(&a, t(LogLevel::Trace, filter));
last(&a, t(Level::Trace, filter));
fn t(lvl: LogLevel, filter: LogLevelFilter) -> Option<LogLevel> {
fn t(lvl: Level, filter: LevelFilter) -> Option<Level> {
if lvl <= filter {Some(lvl)} else {None}
}
}
fn last(state: &State, expected: Option<LogLevel>) {
fn last(state: &State, expected: Option<Level>) {
let mut lvl = state.last_log.lock().unwrap();
assert_eq!(*lvl, expected);
*lvl = None;

View File

@ -1,32 +1,32 @@
#[macro_use] extern crate log;
use std::sync::{Arc, Mutex};
use log::{LogLevel, LogLevelFilter, Log, LogRecord, LogMetadata};
use log::MaxLogLevelFilter;
use log::{Level, LevelFilter, Log, Record, Metadata};
use log::MaxLevelFilter;
#[cfg(feature = "use_std")]
use log::set_logger;
#[cfg(not(feature = "use_std"))]
fn set_logger<M>(make_logger: M) -> Result<(), log::SetLoggerError>
where M: FnOnce(MaxLogLevelFilter) -> Box<Log> {
where M: FnOnce(MaxLevelFilter) -> Box<Log> {
unsafe {
log::set_logger_raw(|x| std::mem::transmute(make_logger(x)))
}
}
struct State {
last_log: Mutex<Option<LogLevel>>,
filter: MaxLogLevelFilter,
last_log: Mutex<Option<Level>>,
filter: MaxLevelFilter,
}
struct Logger(Arc<State>);
impl Log for Logger {
fn enabled(&self, _: &LogMetadata) -> bool {
fn enabled(&self, _: &Metadata) -> bool {
true
}
fn log(&self, record: &LogRecord) {
fn log(&self, record: &Record) {
*self.0.last_log.lock().unwrap() = Some(record.level());
}
}
@ -43,26 +43,26 @@ fn main() {
}).unwrap();
let a = a.unwrap();
test(&a, LogLevelFilter::Off);
test(&a, LogLevelFilter::Error);
test(&a, LogLevelFilter::Warn);
test(&a, LogLevelFilter::Info);
test(&a, LogLevelFilter::Debug);
test(&a, LogLevelFilter::Trace);
test(&a, LevelFilter::Off);
test(&a, LevelFilter::Error);
test(&a, LevelFilter::Warn);
test(&a, LevelFilter::Info);
test(&a, LevelFilter::Debug);
test(&a, LevelFilter::Trace);
}
fn test(a: &State, filter: LogLevelFilter) {
fn test(a: &State, filter: LevelFilter) {
a.filter.set(filter);
error!("");
last(&a, t(LogLevel::Error, filter));
last(&a, t(Level::Error, filter));
warn!("");
last(&a, t(LogLevel::Warn, filter));
last(&a, t(Level::Warn, filter));
info!("");
last(&a, t(LogLevel::Info, filter));
last(&a, t(Level::Info, filter));
debug!("");
if cfg!(debug_assertions) {
last(&a, t(LogLevel::Debug, filter));
last(&a, t(Level::Debug, filter));
} else {
last(&a, None);
}
@ -70,12 +70,12 @@ fn test(a: &State, filter: LogLevelFilter) {
trace!("");
last(&a, None);
fn t(lvl: LogLevel, filter: LogLevelFilter) -> Option<LogLevel> {
fn t(lvl: Level, filter: LevelFilter) -> Option<Level> {
if lvl <= filter {Some(lvl)} else {None}
}
}
fn last(state: &State, expected: Option<LogLevel>) {
fn last(state: &State, expected: Option<Level>) {
let mut lvl = state.last_log.lock().unwrap();
assert_eq!(*lvl, expected);
*lvl = None;