Rocket/core/lib/src/logger.rs

224 lines
6.9 KiB
Rust
Raw Normal View History

//! Rocket's logging infrastructure.
use std::str::FromStr;
use std::fmt;
use log;
use yansi::Paint;
2016-08-24 08:34:00 +00:00
struct RocketLogger(LoggingLevel);
2016-08-24 08:34:00 +00:00
/// Defines the different levels for log messages.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum LoggingLevel {
2018-01-20 18:41:29 +00:00
/// Only shows errors, warnings, and launch information.
2016-08-24 08:34:00 +00:00
Critical,
/// Shows everything except debug and trace information.
Normal,
/// Shows everything.
Debug,
/// Shows nothing.
Off,
2016-08-24 08:34:00 +00:00
}
impl LoggingLevel {
2016-08-24 08:34:00 +00:00
#[inline(always)]
fn to_level_filter(self) -> log::LevelFilter {
match self {
LoggingLevel::Critical => log::LevelFilter::Warn,
LoggingLevel::Normal => log::LevelFilter::Info,
LoggingLevel::Debug => log::LevelFilter::Trace,
LoggingLevel::Off => log::LevelFilter::Off
2016-08-24 08:34:00 +00:00
}
}
}
impl FromStr for LoggingLevel {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let level = match s {
"critical" => LoggingLevel::Critical,
"normal" => LoggingLevel::Normal,
"debug" => LoggingLevel::Debug,
"off" => LoggingLevel::Off,
_ => return Err("a log level (off, debug, normal, critical)")
};
Ok(level)
}
}
impl fmt::Display for LoggingLevel {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let string = match *self {
LoggingLevel::Critical => "critical",
LoggingLevel::Normal => "normal",
LoggingLevel::Debug => "debug",
LoggingLevel::Off => "off"
};
write!(f, "{}", string)
}
}
#[doc(hidden)] #[macro_export]
2018-01-20 18:41:29 +00:00
macro_rules! log_ { ($name:ident: $($args:tt)*) => { $name!(target: "_", $($args)*) }; }
#[doc(hidden)] #[macro_export]
macro_rules! launch_info { ($($args:tt)*) => { info!(target: "launch", $($args)*) } }
2018-01-20 18:41:29 +00:00
#[doc(hidden)] #[macro_export]
macro_rules! launch_info_ { ($($args:tt)*) => { info!(target: "launch_", $($args)*) } }
#[doc(hidden)] #[macro_export]
2016-08-24 08:34:00 +00:00
macro_rules! error_ { ($($args:expr),+) => { log_!(error: $($args),+); }; }
#[doc(hidden)] #[macro_export]
2016-08-24 08:34:00 +00:00
macro_rules! info_ { ($($args:expr),+) => { log_!(info: $($args),+); }; }
#[doc(hidden)] #[macro_export]
2016-08-24 08:34:00 +00:00
macro_rules! trace_ { ($($args:expr),+) => { log_!(trace: $($args),+); }; }
#[doc(hidden)] #[macro_export]
2016-08-24 08:34:00 +00:00
macro_rules! debug_ { ($($args:expr),+) => { log_!(debug: $($args),+); }; }
#[doc(hidden)] #[macro_export]
2016-08-24 08:34:00 +00:00
macro_rules! warn_ { ($($args:expr),+) => { log_!(warn: $($args),+); }; }
impl log::Log for RocketLogger {
#[inline(always)]
fn enabled(&self, record: &log::Metadata) -> bool {
match self.0.to_level_filter().to_level() {
Some(max) => record.level() <= max || record.target().starts_with("launch"),
None => false
}
2016-08-24 08:34:00 +00:00
}
fn log(&self, record: &log::Record) {
// Print nothing if this level isn't enabled and this isn't launch info.
2016-08-24 08:34:00 +00:00
if !self.enabled(record.metadata()) {
return;
}
// Don't print Hyper or Rustls messages unless debug is enabled.
let configged_level = self.0;
let from_hyper = record.module_path().map_or(false, |m| m.starts_with("hyper::"));
let from_rustls = record.module_path().map_or(false, |m| m.starts_with("rustls::"));
2018-01-20 18:41:29 +00:00
if configged_level != LoggingLevel::Debug && (from_hyper || from_rustls) {
2016-10-09 11:29:02 +00:00
return;
}
// In Rocket, we abuse targets with suffix "_" to indicate indentation.
if record.target().ends_with('_') {
if configged_level != LoggingLevel::Critical || record.target().starts_with("launch") {
print!(" {} ", Paint::white("=>"));
}
2016-08-24 08:34:00 +00:00
}
match record.level() {
log::Level::Info => println!("{}", Paint::blue(record.args())),
log::Level::Trace => println!("{}", Paint::purple(record.args())),
log::Level::Error => {
2016-08-24 08:34:00 +00:00
println!("{} {}",
Paint::red("Error:").bold(),
Paint::red(record.args()))
2016-08-24 08:34:00 +00:00
}
log::Level::Warn => {
2016-08-24 08:34:00 +00:00
println!("{} {}",
Paint::yellow("Warning:").bold(),
Paint::yellow(record.args()))
2016-08-24 08:34:00 +00:00
}
log::Level::Debug => {
print!("\n{} ", Paint::blue("-->").bold());
if let Some(file) = record.file() {
print!("{}", Paint::blue(file));
}
if let Some(line) = record.line() {
println!(":{}", Paint::blue(line));
}
println!("{}", record.args());
2016-08-24 08:34:00 +00:00
}
}
}
fn flush(&self) {
// NOOP: We don't buffer any records.
}
2016-08-24 08:34:00 +00:00
}
Overhaul URI types. This is fairly large commit with several entangled logical changes. The primary change in this commit is to completely overhaul how URI handling in Rocket works. Prior to this commit, the `Uri` type acted as an origin API. Its parser was minimal and lenient, allowing URIs that were invalid according to RFC 7230. By contrast, the new `Uri` type brings with it a strict RFC 7230 compliant parser. The `Uri` type now represents any kind of valid URI, not simply `Origin` types. Three new URI types were introduced: * `Origin` - represents valid origin URIs * `Absolute` - represents valid absolute URIs * `Authority` - represents valid authority URIs The `Origin` type replaces `Uri` in many cases: * As fields and method inputs of `Route` * The `&Uri` request guard is now `&Origin` * The `uri!` macro produces an `Origin` instead of a `Uri` The strict nature of URI parsing cascaded into the following changes: * Several `Route` methods now `panic!` on invalid URIs * The `Rocket::mount()` method is (correctly) stricter with URIs * The `Redirect` constructors take a `TryInto<Uri>` type * Dispatching of a `LocalRequest` correctly validates URIs Overall, URIs are now properly and uniformly handled throughout Rocket's codebase, resulting in a more reliable and correct system. In addition to these URI changes, the following changes are also part of this commit: * The `LocalRequest::cloned_dispatch()` method was removed in favor of chaining `.clone().dispatch()`. * The entire Rocket codebase uses `crate` instead of `pub(crate)` as a visibility modifier. * Rocket uses the `crate_visibility_modifier` and `try_from` features. A note on unsafety: this commit introduces many uses of `unsafe` in the URI parser. All of these uses are a result of unsafely transforming byte slices (`&[u8]` or similar) into strings (`&str`). The parser ensures that these casts are safe, but of course, we must label their use `unsafe`. The parser was written to be as generic and efficient as possible and thus can parse directly from byte sources. Rocket, however, does not make use of this fact and so would be able to remove all uses of `unsafe` by parsing from an existing `&str`. This should be considered in the future. Fixes #443. Resolves #263.
2018-07-29 01:26:15 +00:00
crate fn try_init(level: LoggingLevel, verbose: bool) -> bool {
if level == LoggingLevel::Off {
return false;
}
if !::isatty::stdout_isatty() || (cfg!(windows) && !Paint::enable_windows_ascii()) {
Paint::disable();
}
push_max_level(level);
if let Err(e) = log::set_boxed_logger(Box::new(RocketLogger(level))) {
if verbose {
eprintln!("Logger failed to initialize: {}", e);
}
pop_max_level();
return false;
2016-08-24 08:34:00 +00:00
}
true
2016-08-24 08:34:00 +00:00
}
use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
static PUSHED: AtomicBool = AtomicBool::new(false);
2018-02-17 10:12:59 +00:00
static LAST_LOG_FILTER: AtomicUsize = AtomicUsize::new(0);
fn filter_to_usize(filter: log::LevelFilter) -> usize {
match filter {
log::LevelFilter::Off => 0,
log::LevelFilter::Error => 1,
log::LevelFilter::Warn => 2,
log::LevelFilter::Info => 3,
log::LevelFilter::Debug => 4,
log::LevelFilter::Trace => 5,
}
}
fn usize_to_filter(num: usize) -> log::LevelFilter {
2018-02-17 10:12:59 +00:00
match num {
0 => log::LevelFilter::Off,
1 => log::LevelFilter::Error,
2 => log::LevelFilter::Warn,
3 => log::LevelFilter::Info,
4 => log::LevelFilter::Debug,
5 => log::LevelFilter::Trace,
_ => unreachable!("max num is 5 in filter_to_usize")
}
}
Overhaul URI types. This is fairly large commit with several entangled logical changes. The primary change in this commit is to completely overhaul how URI handling in Rocket works. Prior to this commit, the `Uri` type acted as an origin API. Its parser was minimal and lenient, allowing URIs that were invalid according to RFC 7230. By contrast, the new `Uri` type brings with it a strict RFC 7230 compliant parser. The `Uri` type now represents any kind of valid URI, not simply `Origin` types. Three new URI types were introduced: * `Origin` - represents valid origin URIs * `Absolute` - represents valid absolute URIs * `Authority` - represents valid authority URIs The `Origin` type replaces `Uri` in many cases: * As fields and method inputs of `Route` * The `&Uri` request guard is now `&Origin` * The `uri!` macro produces an `Origin` instead of a `Uri` The strict nature of URI parsing cascaded into the following changes: * Several `Route` methods now `panic!` on invalid URIs * The `Rocket::mount()` method is (correctly) stricter with URIs * The `Redirect` constructors take a `TryInto<Uri>` type * Dispatching of a `LocalRequest` correctly validates URIs Overall, URIs are now properly and uniformly handled throughout Rocket's codebase, resulting in a more reliable and correct system. In addition to these URI changes, the following changes are also part of this commit: * The `LocalRequest::cloned_dispatch()` method was removed in favor of chaining `.clone().dispatch()`. * The entire Rocket codebase uses `crate` instead of `pub(crate)` as a visibility modifier. * Rocket uses the `crate_visibility_modifier` and `try_from` features. A note on unsafety: this commit introduces many uses of `unsafe` in the URI parser. All of these uses are a result of unsafely transforming byte slices (`&[u8]` or similar) into strings (`&str`). The parser ensures that these casts are safe, but of course, we must label their use `unsafe`. The parser was written to be as generic and efficient as possible and thus can parse directly from byte sources. Rocket, however, does not make use of this fact and so would be able to remove all uses of `unsafe` by parsing from an existing `&str`. This should be considered in the future. Fixes #443. Resolves #263.
2018-07-29 01:26:15 +00:00
crate fn push_max_level(level: LoggingLevel) {
LAST_LOG_FILTER.store(filter_to_usize(log::max_level()), Ordering::Release);
PUSHED.store(true, Ordering::Release);
log::set_max_level(level.to_level_filter());
}
Overhaul URI types. This is fairly large commit with several entangled logical changes. The primary change in this commit is to completely overhaul how URI handling in Rocket works. Prior to this commit, the `Uri` type acted as an origin API. Its parser was minimal and lenient, allowing URIs that were invalid according to RFC 7230. By contrast, the new `Uri` type brings with it a strict RFC 7230 compliant parser. The `Uri` type now represents any kind of valid URI, not simply `Origin` types. Three new URI types were introduced: * `Origin` - represents valid origin URIs * `Absolute` - represents valid absolute URIs * `Authority` - represents valid authority URIs The `Origin` type replaces `Uri` in many cases: * As fields and method inputs of `Route` * The `&Uri` request guard is now `&Origin` * The `uri!` macro produces an `Origin` instead of a `Uri` The strict nature of URI parsing cascaded into the following changes: * Several `Route` methods now `panic!` on invalid URIs * The `Rocket::mount()` method is (correctly) stricter with URIs * The `Redirect` constructors take a `TryInto<Uri>` type * Dispatching of a `LocalRequest` correctly validates URIs Overall, URIs are now properly and uniformly handled throughout Rocket's codebase, resulting in a more reliable and correct system. In addition to these URI changes, the following changes are also part of this commit: * The `LocalRequest::cloned_dispatch()` method was removed in favor of chaining `.clone().dispatch()`. * The entire Rocket codebase uses `crate` instead of `pub(crate)` as a visibility modifier. * Rocket uses the `crate_visibility_modifier` and `try_from` features. A note on unsafety: this commit introduces many uses of `unsafe` in the URI parser. All of these uses are a result of unsafely transforming byte slices (`&[u8]` or similar) into strings (`&str`). The parser ensures that these casts are safe, but of course, we must label their use `unsafe`. The parser was written to be as generic and efficient as possible and thus can parse directly from byte sources. Rocket, however, does not make use of this fact and so would be able to remove all uses of `unsafe` by parsing from an existing `&str`. This should be considered in the future. Fixes #443. Resolves #263.
2018-07-29 01:26:15 +00:00
crate fn pop_max_level() {
if PUSHED.load(Ordering::Acquire) {
log::set_max_level(usize_to_filter(LAST_LOG_FILTER.load(Ordering::Acquire)));
}
}
#[doc(hidden)]
pub fn init(level: LoggingLevel) -> bool {
try_init(level, true)
}
// Expose logging macros as (hidden) funcions for use by core/contrib codegen.
macro_rules! external_log_function {
($fn_name:ident: $macro_name:ident) => (
#[doc(hidden)] #[inline(always)]
pub fn $fn_name(msg: &str) { $macro_name!("{}", msg); }
)
}
external_log_function!(log_error: error);
external_log_function!(log_error_: error_);
external_log_function!(log_warn: warn);
external_log_function!(log_warn_: warn_);