From d01ca9cc5d137b606dc4a4259f501150e6b92117 Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Thu, 2 May 2024 19:12:25 -0700 Subject: [PATCH] wip: remove all traces of 'log' --- benchmarks/src/routing.rs | 2 +- contrib/db_pools/lib/src/pool.rs | 14 +- contrib/dyn_templates/src/fairing.rs | 2 +- core/codegen/src/attribute/route/mod.rs | 28 +-- core/codegen/src/exports.rs | 1 - core/lib/Cargo.toml | 23 +- core/lib/fuzz/targets/collision-matching.rs | 2 +- core/lib/src/config/config.rs | 21 +- core/lib/src/config/mod.rs | 2 +- core/lib/src/config/tests.rs | 8 +- core/lib/src/fairing/fairings.rs | 2 +- core/lib/src/lib.rs | 2 +- core/lib/src/local/client.rs | 2 +- core/lib/src/log.rs | 252 -------------------- core/lib/src/rocket.rs | 6 +- core/lib/src/shield/shield.rs | 2 +- core/lib/src/trace.rs | 15 ++ examples/tls/src/redirector.rs | 3 +- testbench/src/main.rs | 24 +- 19 files changed, 84 insertions(+), 327 deletions(-) delete mode 100644 core/lib/src/log.rs create mode 100644 core/lib/src/trace.rs diff --git a/benchmarks/src/routing.rs b/benchmarks/src/routing.rs index 48e7b165c1..3d57b40974 100644 --- a/benchmarks/src/routing.rs +++ b/benchmarks/src/routing.rs @@ -80,7 +80,7 @@ fn generate_matching_requests<'c>(client: &'c Client, routes: &[Route]) -> Vec) -> Client { let config = Config { profile: Config::RELEASE_PROFILE, - log_level: rocket::config::LogLevel::Off, + // log_level: rocket::config::LogLevel::Off, cli_colors: config::CliColors::Never, shutdown: config::ShutdownConfig { ctrlc: false, diff --git a/contrib/db_pools/lib/src/pool.rs b/contrib/db_pools/lib/src/pool.rs index 371c2f7659..9661a17aff 100644 --- a/contrib/db_pools/lib/src/pool.rs +++ b/contrib/db_pools/lib/src/pool.rs @@ -270,7 +270,7 @@ mod deadpool_old { mod sqlx { use sqlx::ConnectOptions; use super::{Duration, Error, Config, Figment}; - use rocket::config::LogLevel; + // use rocket::config::LogLevel; type Options = <::Connection as sqlx::Connection>::Options; @@ -302,12 +302,12 @@ mod sqlx { specialize(&mut opts, &config); opts = opts.disable_statement_logging(); - if let Ok(level) = figment.extract_inner::(rocket::Config::LOG_LEVEL) { - if !matches!(level, LogLevel::Normal | LogLevel::Off) { - opts = opts.log_statements(level.into()) - .log_slow_statements(level.into(), Duration::default()); - } - } + // if let Ok(level) = figment.extract_inner::(rocket::Config::LOG_LEVEL) { + // if !matches!(level, LogLevel::Normal | LogLevel::Off) { + // opts = opts.log_statements(level.into()) + // .log_slow_statements(level.into(), Duration::default()); + // } + // } sqlx::pool::PoolOptions::new() .max_connections(config.max_connections as u32) diff --git a/contrib/dyn_templates/src/fairing.rs b/contrib/dyn_templates/src/fairing.rs index 169bc2073b..d8d7ef3e67 100644 --- a/contrib/dyn_templates/src/fairing.rs +++ b/contrib/dyn_templates/src/fairing.rs @@ -55,7 +55,7 @@ impl Fairing for TemplateFairing { } async fn on_liftoff(&self, rocket: &Rocket) { - use rocket::{figment::Source, log::PaintExt, yansi::Paint}; + use rocket::{figment::Source, yansi::Paint}; let cm = rocket.state::() .expect("Template ContextManager registered in on_ignite"); diff --git a/core/codegen/src/attribute/route/mod.rs b/core/codegen/src/attribute/route/mod.rs index b5fb59687b..5b8bfad925 100644 --- a/core/codegen/src/attribute/route/mod.rs +++ b/core/codegen/src/attribute/route/mod.rs @@ -41,7 +41,7 @@ fn query_decls(route: &Route) -> Option { } define_spanned_export!(Span::call_site() => - __req, __data, _log, _form, Outcome, _Ok, _Err, _Some, _None, Status + __req, __data, _form, Outcome, _Ok, _Err, _Some, _None, Status ); // Record all of the static parameters for later filtering. @@ -105,8 +105,8 @@ fn query_decls(route: &Route) -> Option { )* if !__e.is_empty() { - #_log::warn_!("Query string failed to match route declaration."); - for _err in __e { #_log::warn_!("{}", _err); } + ::rocket::warn_!("Query string failed to match route declaration."); + for _err in __e { ::rocket::warn_!("{}", _err); } return #Outcome::Forward((#__data, #Status::UnprocessableEntity)); } @@ -118,18 +118,18 @@ fn query_decls(route: &Route) -> Option { fn request_guard_decl(guard: &Guard) -> TokenStream { let (ident, ty) = (guard.fn_ident.rocketized(), &guard.ty); define_spanned_export!(ty.span() => - __req, __data, _request, _log, FromRequest, Outcome + __req, __data, _request, FromRequest, Outcome ); quote_spanned! { ty.span() => let #ident: #ty = match <#ty as #FromRequest>::from_request(#__req).await { #Outcome::Success(__v) => __v, #Outcome::Forward(__e) => { - #_log::warn_!("Request guard `{}` is forwarding.", stringify!(#ty)); + ::rocket::warn_!("Request guard `{}` is forwarding.", stringify!(#ty)); return #Outcome::Forward((#__data, __e)); }, #Outcome::Error((__c, __e)) => { - #_log::warn_!("Request guard `{}` failed: {:?}.", stringify!(#ty), __e); + ::rocket::warn_!("Request guard `{}` failed: {:?}.", stringify!(#ty), __e); return #Outcome::Error(__c); } }; @@ -139,13 +139,13 @@ fn request_guard_decl(guard: &Guard) -> TokenStream { fn param_guard_decl(guard: &Guard) -> TokenStream { let (i, name, ty) = (guard.index, &guard.name, &guard.ty); define_spanned_export!(ty.span() => - __req, __data, _log, _None, _Some, _Ok, _Err, + __req, __data, _None, _Some, _Ok, _Err, Outcome, FromSegments, FromParam, Status ); // Returned when a dynamic parameter fails to parse. let parse_error = quote!({ - #_log::warn_!("Parameter guard `{}: {}` is forwarding: {:?}.", + ::rocket::warn_!("Parameter guard `{}: {}` is forwarding: {:?}.", #name, stringify!(#ty), __error); #Outcome::Forward((#__data, #Status::UnprocessableEntity)) @@ -161,9 +161,9 @@ fn param_guard_decl(guard: &Guard) -> TokenStream { #_Err(__error) => return #parse_error, }, #_None => { - #_log::error_!("Internal invariant broken: dyn param {} not found.", #i); - #_log::error_!("Please report this to the Rocket issue tracker."); - #_log::error_!("https://github.com/rwf2/Rocket/issues"); + ::rocket::error_!("Internal invariant broken: dyn param {} not found.", #i); + ::rocket::error_!("Please report this to the Rocket issue tracker."); + ::rocket::error_!("https://github.com/rwf2/Rocket/issues"); return #Outcome::Forward((#__data, #Status::InternalServerError)); } } @@ -182,17 +182,17 @@ fn param_guard_decl(guard: &Guard) -> TokenStream { fn data_guard_decl(guard: &Guard) -> TokenStream { let (ident, ty) = (guard.fn_ident.rocketized(), &guard.ty); - define_spanned_export!(ty.span() => _log, __req, __data, FromData, Outcome); + define_spanned_export!(ty.span() => __req, __data, FromData, Outcome); quote_spanned! { ty.span() => let #ident: #ty = match <#ty as #FromData>::from_data(#__req, #__data).await { #Outcome::Success(__d) => __d, #Outcome::Forward((__d, __e)) => { - #_log::warn_!("Data guard `{}` is forwarding.", stringify!(#ty)); + ::rocket::warn_!("Data guard `{}` is forwarding.", stringify!(#ty)); return #Outcome::Forward((__d, __e)); } #Outcome::Error((__c, __e)) => { - #_log::warn_!("Data guard `{}` failed: {:?}.", stringify!(#ty), __e); + ::rocket::warn_!("Data guard `{}` failed: {:?}.", stringify!(#ty), __e); return #Outcome::Error(__c); } }; diff --git a/core/codegen/src/exports.rs b/core/codegen/src/exports.rs index 7ceff13a0c..6dfb4eb3ee 100644 --- a/core/codegen/src/exports.rs +++ b/core/codegen/src/exports.rs @@ -71,7 +71,6 @@ define_exported_paths! { _route => ::rocket::route, _catcher => ::rocket::catcher, _sentinel => ::rocket::sentinel, - _log => ::rocket::log, _form => ::rocket::form::prelude, _http => ::rocket::http, _uri => ::rocket::http::uri, diff --git a/core/lib/Cargo.toml b/core/lib/Cargo.toml index 1383006f6a..094754b334 100644 --- a/core/lib/Cargo.toml +++ b/core/lib/Cargo.toml @@ -56,10 +56,10 @@ x509-parser = { version = "0.16", optional = true } http = "1" bytes = "1.4" hyper = { version = "1.1", default-features = false, features = ["http1", "server"] } +hyper-util = { version = "0.1.3", default-features = false, features = ["http1", "server", "tokio"] } # Non-optional, core dependencies from here on out. yansi = { version = "1.0.1", features = ["detect-tty"] } -log = { version = "0.4", features = ["std"] } num_cpus = "1.0" time = { version = "0.3", features = ["macros", "parsing"] } memchr = "2" # TODO: Use pear instead. @@ -83,10 +83,14 @@ cookie = { version = "0.18", features = ["percent-encode"] } futures = { version = "0.3.30", default-features = false, features = ["std"] } state = "0.6" -[dependencies.hyper-util] -version = "0.1.3" -default-features = false -features = ["http1", "server", "tokio"] +[dependencies.rocket_codegen] +version = "0.6.0-dev" +path = "../codegen" + +[dependencies.rocket_http] +version = "0.6.0-dev" +path = "../http" +features = ["serde"] [dependencies.tokio] version = "1.35.1" @@ -97,15 +101,6 @@ version = "0.7" default-features = false features = ["io"] -[dependencies.rocket_codegen] -version = "0.6.0-dev" -path = "../codegen" - -[dependencies.rocket_http] -version = "0.6.0-dev" -path = "../http" -features = ["serde"] - [dependencies.rustls] version = "0.23" default-features = false diff --git a/core/lib/fuzz/targets/collision-matching.rs b/core/lib/fuzz/targets/collision-matching.rs index 2af226ac02..e82d8c2739 100644 --- a/core/lib/fuzz/targets/collision-matching.rs +++ b/core/lib/fuzz/targets/collision-matching.rs @@ -185,7 +185,7 @@ type TestData<'a> = ( fn fuzz((route_a, route_b, req): TestData<'_>) { let rocket = rocket::custom(rocket::Config { workers: 2, - log_level: rocket::log::LogLevel::Off, + // log_level: rocket::log::LogLevel::Off, cli_colors: rocket::config::CliColors::Never, ..rocket::Config::debug_default() }); diff --git a/core/lib/src/config/config.rs b/core/lib/src/config/config.rs index 00560b768c..d234a89b29 100644 --- a/core/lib/src/config/config.rs +++ b/core/lib/src/config/config.rs @@ -4,8 +4,9 @@ use figment::value::{Map, Dict, magic::RelativePathBuf}; use serde::{Deserialize, Serialize}; use yansi::{Paint, Style, Color::Primary}; -use crate::log::PaintExt; -use crate::config::{LogLevel, ShutdownConfig, Ident, CliColors}; +// use crate::log::PaintExt; +// use crate::config::{LogLevel, ShutdownConfig, Ident, CliColors}; +use crate::config::{ShutdownConfig, Ident, CliColors}; use crate::request::{self, Request, FromRequest}; use crate::http::uncased::Uncased; use crate::data::Limits; @@ -122,8 +123,8 @@ pub struct Config { pub secret_key: SecretKey, /// Graceful shutdown configuration. **(default: [`ShutdownConfig::default()`])** pub shutdown: ShutdownConfig, - /// Max level to log. **(default: _debug_ `normal` / _release_ `critical`)** - pub log_level: LogLevel, + // /// Max level to log. **(default: _debug_ `normal` / _release_ `critical`)** + // pub log_level: LogLevel, /// Whether to use colors and emoji when logging. **(default: /// [`CliColors::Auto`])** pub cli_colors: CliColors, @@ -201,7 +202,7 @@ impl Config { #[cfg(feature = "secrets")] secret_key: SecretKey::zero(), shutdown: ShutdownConfig::default(), - log_level: LogLevel::Normal, + // log_level: LogLevel::Normal, cli_colors: CliColors::Auto, __non_exhaustive: (), } @@ -225,7 +226,7 @@ impl Config { pub fn release_default() -> Config { Config { profile: Self::RELEASE_PROFILE, - log_level: LogLevel::Critical, + // log_level: LogLevel::Critical, ..Config::debug_default() } } @@ -327,9 +328,9 @@ impl Config { #[inline] pub(crate) fn trace_print(&self, figment: &Figment) { - if self.log_level != LogLevel::Debug { - return; - } + // if self.log_level != LogLevel::Debug { + // return; + // } trace!("-- configuration trace information --"); for param in Self::PARAMETERS { @@ -536,7 +537,7 @@ pub fn bail_with_config_error(error: figment::Error) -> T { pub fn pretty_print_error(error: figment::Error) { use figment::error::{Kind, OneOf}; - crate::log::init_default(); + // crate::log::init_default(); error!("Failed to extract valid configuration."); for e in error { fn w(v: T) -> yansi::Painted { Paint::new(v).primary() } diff --git a/core/lib/src/config/mod.rs b/core/lib/src/config/mod.rs index c003a43a4c..376e878ff4 100644 --- a/core/lib/src/config/mod.rs +++ b/core/lib/src/config/mod.rs @@ -122,7 +122,7 @@ pub use ident::Ident; pub use config::Config; pub use cli_colors::CliColors; -pub use crate::log::LogLevel; +// pub use crate::log::LogLevel; pub use crate::shutdown::ShutdownConfig; #[cfg(feature = "tls")] diff --git a/core/lib/src/config/tests.rs b/core/lib/src/config/tests.rs index b5e3429f4c..d3bd640dda 100644 --- a/core/lib/src/config/tests.rs +++ b/core/lib/src/config/tests.rs @@ -1,7 +1,7 @@ use figment::{Figment, Profile}; use pretty_assertions::assert_eq; -use crate::log::LogLevel; +// use crate::log::LogLevel; use crate::data::{Limits, ToByteUnit}; use crate::config::{Config, CliColors}; @@ -65,7 +65,7 @@ fn test_toml_file() { workers: 20, ident: ident!("Something Cool"), keep_alive: 10, - log_level: LogLevel::Off, + // log_level: LogLevel::Off, cli_colors: CliColors::Never, ..Config::default() }); @@ -84,7 +84,7 @@ fn test_toml_file() { workers: 20, ident: ident!("Something Else Cool"), keep_alive: 10, - log_level: LogLevel::Off, + // log_level: LogLevel::Off, cli_colors: CliColors::Never, ..Config::default() }); @@ -102,7 +102,7 @@ fn test_toml_file() { assert_eq!(config, Config { workers: 20, keep_alive: 10, - log_level: LogLevel::Off, + // log_level: LogLevel::Off, cli_colors: CliColors::Never, ..Config::default() }); diff --git a/core/lib/src/fairing/fairings.rs b/core/lib/src/fairing/fairings.rs index 12a99c08c4..31072814ba 100644 --- a/core/lib/src/fairing/fairings.rs +++ b/core/lib/src/fairing/fairings.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; use crate::{Rocket, Request, Response, Data, Build, Orbit}; use crate::fairing::{Fairing, Info, Kind}; -use crate::log::PaintExt; +// use crate::log::PaintExt; use yansi::Paint; diff --git a/core/lib/src/lib.rs b/core/lib/src/lib.rs index be2e2d8ed7..8e56ddc604 100644 --- a/core/lib/src/lib.rs +++ b/core/lib/src/lib.rs @@ -123,7 +123,7 @@ pub use time; #[doc(hidden)] #[macro_use] -pub mod log; +pub mod trace; #[macro_use] pub mod outcome; #[macro_use] diff --git a/core/lib/src/local/client.rs b/core/lib/src/local/client.rs index 8abc4a4864..9dad0c4749 100644 --- a/core/lib/src/local/client.rs +++ b/core/lib/src/local/client.rs @@ -138,7 +138,7 @@ macro_rules! pub_client_impl { use crate::config; let figment = rocket.figment().clone() - .merge((config::Config::LOG_LEVEL, config::LogLevel::Debug)) + // .merge((config::Config::LOG_LEVEL, config::LogLevel::Debug)) .select(config::Config::DEBUG_PROFILE); Self::tracked(rocket.reconfigure(figment)) $(.$suffix)? diff --git a/core/lib/src/log.rs b/core/lib/src/log.rs deleted file mode 100644 index 69f368c754..0000000000 --- a/core/lib/src/log.rs +++ /dev/null @@ -1,252 +0,0 @@ -//! Rocket's logging infrastructure. - -use std::fmt; -use std::str::FromStr; -use std::sync::atomic::{AtomicBool, Ordering}; - -use serde::{de, Serialize, Serializer, Deserialize, Deserializer}; -use yansi::{Paint, Painted, Condition}; - -/// Reexport the `log` crate as `private`. -pub use log as private; - -// Expose logging macros (hidden) for use by core/contrib codegen. -macro_rules! define_log_macro { - ($name:ident: $kind:ident, $target:expr, $d:tt) => ( - #[doc(hidden)] - #[macro_export] - macro_rules! $name { - ($d ($t:tt)*) => ($crate::log::private::$kind!(target: $target, $d ($t)*)) - } - ); - ($name:ident ($indented:ident): $kind:ident, $target:expr, $d:tt) => ( - define_log_macro!($name: $kind, $target, $d); - define_log_macro!($indented: $kind, concat!($target, "::_"), $d); - ); - ($kind:ident, $indented:ident) => ( - define_log_macro!($kind: $kind, module_path!(), $); - define_log_macro!($indented: $kind, concat!(module_path!(), "::_"), $); - - pub use $indented; - ); -} - -define_log_macro!(error, error_); -define_log_macro!(warn, warn_); -define_log_macro!(info, info_); -define_log_macro!(debug, debug_); -define_log_macro!(trace, trace_); -define_log_macro!(launch_meta (launch_meta_): info, "rocket::launch", $); -define_log_macro!(launch_info (launch_msg_): warn, "rocket::launch", $); - -// `print!` panics when stdout isn't available, but this macro doesn't. See -// rwf2/Rocket#2019 and rust-lang/rust#46016 for more. -// -// Unfortunately, `libtest` captures output by replacing a special sink that -// `print!`, and _only_ `print!`, writes to. Using `write!` directly bypasses -// this sink. As a result, using this better implementation for logging means -// that test log output isn't captured, muddying `cargo test` output. -// -// As a compromise, we only use this better implementation when we're not -// compiled with `debug_assertions` or running tests, so at least tests run in -// debug-mode won't spew output. NOTE: `cfg(test)` alone isn't sufficient: the -// crate is compiled normally for integration tests. -#[cfg(not(any(debug_assertions, test, doctest)))] -macro_rules! write_out { - ($($arg:tt)*) => ({ - use std::io::{Write, stdout, stderr}; - let _ = write!(stdout(), $($arg)*).or_else(|e| write!(stderr(), "{}", e)); - }) -} - -#[cfg(any(debug_assertions, test, doctest))] -macro_rules! write_out { - ($($arg:tt)*) => (print!($($arg)*)) -} - -#[derive(Debug)] -struct RocketLogger; - -/// Defines the maximum level of log messages to show. -#[derive(PartialEq, Eq, Debug, Clone, Copy)] -pub enum LogLevel { - /// Only shows errors and warnings: `"critical"`. - Critical, - /// Shows everything except debug and trace information: `"normal"`. - Normal, - /// Shows everything: `"debug"`. - Debug, - /// Shows nothing: "`"off"`". - Off, -} - -pub trait PaintExt: Sized { - fn emoji(self) -> Painted; -} - -// Whether a record is a special `launch_{meta,info}!` record. -fn is_launch_record(record: &log::Metadata<'_>) -> bool { - record.target().contains("rocket::launch") -} - -impl log::Log for RocketLogger { - #[inline(always)] - fn enabled(&self, record: &log::Metadata<'_>) -> bool { - match log::max_level().to_level() { - Some(max) => record.level() <= max || is_launch_record(record), - None => false - } - } - - fn log(&self, record: &log::Record<'_>) { - // Print nothing if this level isn't enabled and this isn't launch info. - if !self.enabled(record.metadata()) { - return; - } - - // Don't print Hyper, Rustls or r2d2 messages unless debug is enabled. - let max = log::max_level(); - let from = |path| record.module_path().map_or(false, |m| m.starts_with(path)); - let debug_only = from("hyper") || from("rustls") || from("r2d2"); - if log::LevelFilter::from(LogLevel::Debug) > max && debug_only { - return; - } - - // In Rocket, we abuse targets with suffix "_" to indicate indentation. - let indented = record.target().ends_with('_'); - if indented { - write_out!(" {} ", ">>".bold()); - } - - // Downgrade a physical launch `warn` to logical `info`. - let level = is_launch_record(record.metadata()) - .then_some(log::Level::Info) - .unwrap_or_else(|| record.level()); - - match level { - log::Level::Error if !indented => { - write_out!("{} {}\n", "Error:".red().bold(), record.args().red().wrap()); - } - log::Level::Warn if !indented => { - write_out!("{} {}\n", "Warning:".yellow().bold(), record.args().yellow().wrap()); - } - log::Level::Info => write_out!("{}\n", record.args().blue().wrap()), - log::Level::Trace => write_out!("{}\n", record.args().magenta().wrap()), - log::Level::Warn => write_out!("{}\n", record.args().yellow().wrap()), - log::Level::Error => write_out!("{}\n", &record.args().red().wrap()), - log::Level::Debug => { - write_out!("\n{} ", "-->".blue().bold()); - if let Some(file) = record.file() { - write_out!("{}", file.blue()); - } - - if let Some(line) = record.line() { - write_out!(":{}\n", line.blue()); - } - - write_out!("\t{}\n", record.args()); - } - } - } - - fn flush(&self) { - // NOOP: We don't buffer any records. - } -} - -static ROCKET_LOGGER_SET: AtomicBool = AtomicBool::new(false); - -pub(crate) fn init_default() { - if !ROCKET_LOGGER_SET.load(Ordering::Acquire) { - crate::log::init(&crate::Config::debug_default()) - } -} - -pub(crate) fn init(config: &crate::Config) { - // Try to initialize Rocket's logger, recording if we succeeded. - if log::set_boxed_logger(Box::new(RocketLogger)).is_ok() { - ROCKET_LOGGER_SET.store(true, Ordering::Release); - } - - // Always disable colors if requested or if the stdout/err aren't TTYs. - let should_color = match config.cli_colors { - crate::config::CliColors::Always => Condition::ALWAYS, - crate::config::CliColors::Auto => Condition::DEFAULT, - crate::config::CliColors::Never => Condition::NEVER, - }; - - yansi::whenever(should_color); - - // Set Rocket-logger specific settings only if Rocket's logger is set. - if ROCKET_LOGGER_SET.load(Ordering::Acquire) { - log::set_max_level(config.log_level.into()); - } -} - -impl From for log::LevelFilter { - fn from(level: LogLevel) -> Self { - match level { - LogLevel::Critical => log::LevelFilter::Warn, - LogLevel::Normal => log::LevelFilter::Info, - LogLevel::Debug => log::LevelFilter::Trace, - LogLevel::Off => log::LevelFilter::Off - } - } -} - -impl LogLevel { - fn as_str(&self) -> &str { - match self { - LogLevel::Critical => "critical", - LogLevel::Normal => "normal", - LogLevel::Debug => "debug", - LogLevel::Off => "off", - } - } -} - -impl FromStr for LogLevel { - type Err = &'static str; - - fn from_str(s: &str) -> Result { - let level = match &*s.to_ascii_lowercase() { - "critical" => LogLevel::Critical, - "normal" => LogLevel::Normal, - "debug" => LogLevel::Debug, - "off" => LogLevel::Off, - _ => return Err("a log level (off, debug, normal, critical)") - }; - - Ok(level) - } -} - -impl fmt::Display for LogLevel { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.as_str()) - } -} - -impl Serialize for LogLevel { - fn serialize(&self, ser: S) -> Result { - ser.serialize_str(self.as_str()) - } -} - -impl<'de> Deserialize<'de> for LogLevel { - fn deserialize>(de: D) -> Result { - let string = String::deserialize(de)?; - LogLevel::from_str(&string).map_err(|_| de::Error::invalid_value( - de::Unexpected::Str(&string), - &figment::error::OneOf( &["critical", "normal", "debug", "off"]) - )) - } -} - -impl PaintExt for &str { - /// Paint::masked(), but hidden on Windows due to broken output. See #1122. - fn emoji(self) -> Painted { - #[cfg(windows)] { Paint::new("").mask() } - #[cfg(not(windows))] { Paint::new(self).mask() } - } -} diff --git a/core/lib/src/rocket.rs b/core/lib/src/rocket.rs index 063089fe49..8c46a9d2d0 100644 --- a/core/lib/src/rocket.rs +++ b/core/lib/src/rocket.rs @@ -20,7 +20,7 @@ use crate::phase::{Stateful, StateRef, State}; use crate::http::uri::Origin; use crate::http::ext::IntoOwned; use crate::error::{Error, ErrorKind}; -use crate::log::PaintExt; +// use crate::log::PaintExt; /// The application server itself. /// @@ -187,7 +187,7 @@ impl Rocket { pub fn custom(provider: T) -> Self { // We initialize the logger here so that logging from fairings and so on // are visible; we use the final config to set a max log-level in ignite - crate::log::init_default(); + // crate::log::init_default(); let rocket: Rocket = Rocket(Building { figment: Figment::from(provider), @@ -541,7 +541,7 @@ impl Rocket { // Extract the configuration; initialize the logger. #[allow(unused_mut)] let mut config = Config::try_from(&self.figment).map_err(ErrorKind::Config)?; - crate::log::init(&config); + // crate::log::init(&config); // Check for safely configured secrets. #[cfg(feature = "secrets")] diff --git a/core/lib/src/shield/shield.rs b/core/lib/src/shield/shield.rs index 65e0ffcd4b..37ab117148 100644 --- a/core/lib/src/shield/shield.rs +++ b/core/lib/src/shield/shield.rs @@ -6,7 +6,7 @@ use yansi::Paint; use crate::{Rocket, Request, Response, Orbit, Config}; use crate::fairing::{Fairing, Info, Kind}; use crate::http::{Header, uncased::UncasedStr}; -use crate::log::PaintExt; +// use crate::log::PaintExt; use crate::shield::*; /// A [`Fairing`] that injects browser security and privacy headers into all diff --git a/core/lib/src/trace.rs b/core/lib/src/trace.rs new file mode 100644 index 0000000000..846a26a2ec --- /dev/null +++ b/core/lib/src/trace.rs @@ -0,0 +1,15 @@ +macro_rules! declare_macro { + ($($name:ident),*) => ( + $(declare_macro!([$] $name);)* + ); + + ([$d:tt] $name:ident) => ( + #[macro_export] + macro_rules! $name { + ($d ($token:tt)*) => ({}) + } + ); +} + +declare_macro!(log, log_, launch_info, launch_info_, launch_meta, launch_meta_, + error, error_, info, info_, trace, trace_, debug, debug_, warn, warn_); diff --git a/examples/tls/src/redirector.rs b/examples/tls/src/redirector.rs index 21e4c76e98..7659da08a0 100644 --- a/examples/tls/src/redirector.rs +++ b/examples/tls/src/redirector.rs @@ -3,7 +3,6 @@ use std::net::SocketAddr; use rocket::http::Status; -use rocket::log::LogLevel; use rocket::{route, Error, Request, Data, Route, Orbit, Rocket, Ignite}; use rocket::fairing::{Fairing, Info, Kind}; use rocket::response::Redirect; @@ -85,7 +84,7 @@ impl Fairing for Redirector { let config = Config { tls_addr, server: rocket::Config { - log_level: LogLevel::Critical, + // log_level: LogLevel::Critical, ..rocket.config().clone() }, }; diff --git a/testbench/src/main.rs b/testbench/src/main.rs index 002fbb061e..2ea7a81c53 100644 --- a/testbench/src/main.rs +++ b/testbench/src/main.rs @@ -79,8 +79,8 @@ fn run_fail() -> Result<()> { }; if let Err(Error::Liftoff(stdout, _)) = server { - assert!(stdout.contains("Rocket failed to launch due to failing fairings")); - assert!(stdout.contains("FailNow")); + // assert!(stdout.contains("Rocket failed to launch due to failing fairings")); + // assert!(stdout.contains("FailNow")); } else { panic!("unexpected result: {server:#?}"); } @@ -109,9 +109,9 @@ fn infinite() -> Result<()> { server.terminate()?; let stdout = server.read_stdout()?; - assert!(stdout.contains("Rocket has launched on http")); - assert!(stdout.contains("GET /")); - assert!(stdout.contains("Graceful shutdown completed")); + // assert!(stdout.contains("Rocket has launched on http")); + // assert!(stdout.contains("GET /")); + // assert!(stdout.contains("Graceful shutdown completed")); Ok(()) } @@ -133,9 +133,9 @@ fn tls_info() -> Result<()> { server.terminate()?; let stdout = server.read_stdout()?; - assert!(stdout.contains("Rocket has launched on https")); - assert!(stdout.contains("Graceful shutdown completed")); - assert!(stdout.contains("GET /")); + // assert!(stdout.contains("Rocket has launched on https")); + // assert!(stdout.contains("Graceful shutdown completed")); + // assert!(stdout.contains("GET /")); let server = Server::spawn((), |(token, _)| { let rocket = rocket::build() @@ -352,8 +352,8 @@ fn tcp_unix_listener_fail() -> Result<()> { }; if let Err(Error::Liftoff(stdout, _)) = server { - assert!(stdout.contains("expected valid TCP (ip) or unix (path)")); - assert!(stdout.contains("default.address")); + // assert!(stdout.contains("expected valid TCP (ip) or unix (path)")); + // assert!(stdout.contains("default.address")); } else { panic!("unexpected result: {server:#?}"); } @@ -364,7 +364,7 @@ fn tcp_unix_listener_fail() -> Result<()> { }); if let Err(Error::Liftoff(stdout, _)) = server { - assert!(stdout.contains("invalid tcp endpoint: unix:foo")); + // assert!(stdout.contains("invalid tcp endpoint: unix:foo")); } else { panic!("unexpected result: {server:#?}"); } @@ -374,7 +374,7 @@ fn tcp_unix_listener_fail() -> Result<()> { }); if let Err(Error::Liftoff(stdout, _)) = server { - assert!(stdout.contains("invalid unix endpoint: tcp:127.0.0.1:8000")); + // assert!(stdout.contains("invalid unix endpoint: tcp:127.0.0.1:8000")); } else { panic!("unexpected result: {server:#?}"); }