diff --git a/Cargo.lock b/Cargo.lock index c8042ba43ec8d..160e229c35fa3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1454,20 +1454,6 @@ dependencies = [ "miniz_oxide", ] -[[package]] -name = "flexi_logger" -version = "0.15.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33897654c23a50cebab45e18356f69fb771c9949a6928344fb1f01ffccc7c5f3" -dependencies = [ - "chrono", - "glob 0.3.0", - "log", - "regex", - "thiserror", - "yansi", -] - [[package]] name = "fnv" version = "1.0.6" @@ -6158,8 +6144,8 @@ dependencies = [ "atty", "chrono", "derive_more", + "env_logger 0.7.1", "fdlimit", - "flexi_logger", "futures 0.3.5", "lazy_static", "log", @@ -9943,12 +9929,6 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "yansi" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fc79f4a1e39857fc00c3f662cbf2651c771f00e9c15fe2abc341806bd46bd71" - [[package]] name = "zeroize" version = "1.1.0" diff --git a/bin/node/bench/src/main.rs b/bin/node/bench/src/main.rs index 4fcff297a6f64..11820247112f8 100644 --- a/bin/node/bench/src/main.rs +++ b/bin/node/bench/src/main.rs @@ -77,7 +77,7 @@ fn main() { let opt = Opt::from_args(); if !opt.json { - sc_cli::init_logger("", None).expect("init_logger should not fail."); + sc_cli::init_logger(""); } let mut import_benchmarks = Vec::new(); diff --git a/client/cli/Cargo.toml b/client/cli/Cargo.toml index 4523769e735e1..3bf480f0b1eee 100644 --- a/client/cli/Cargo.toml +++ b/client/cli/Cargo.toml @@ -13,7 +13,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] derive_more = "0.99.2" -flexi_logger = "0.15.7" +env_logger = "0.7.0" log = "0.4.8" atty = "0.2.13" regex = "1.3.1" diff --git a/client/cli/src/config.rs b/client/cli/src/config.rs index aee370c978d46..fa3f09116c314 100644 --- a/client/cli/src/config.rs +++ b/client/cli/src/config.rs @@ -21,10 +21,9 @@ use crate::arg_enums::Database; use crate::error::Result; use crate::{ - DatabaseParams, ImportParams, KeystoreParams, NetworkParams, NodeKeyParams, + init_logger, DatabaseParams, ImportParams, KeystoreParams, NetworkParams, NodeKeyParams, OffchainWorkerParams, PruningParams, SharedParams, SubstrateCli, }; -use crate::logger::{LogRotationOpt, init_logger}; use names::{Generator, Name}; use sc_client_api::execution_extensions::ExecutionStrategies; use sc_service::config::{ @@ -489,13 +488,6 @@ pub trait CliConfiguration: Sized { Ok(self.shared_params().log_filters().join(",")) } - /// Get the log directory for logging. - /// - /// By default this is retrieved from `SharedParams`. - fn log_rotation_opt(&self) -> Result { - Ok(self.shared_params().log_rotation_opt().clone()) - } - /// Initialize substrate. This must be done only once. /// /// This method: @@ -505,12 +497,11 @@ pub trait CliConfiguration: Sized { /// 3. Initialize the logger fn init(&self) -> Result<()> { let logger_pattern = self.log_filters()?; - let log_rotation_opt = self.log_rotation_opt()?; sp_panic_handler::set(&C::support_url(), &C::impl_version()); fdlimit::raise_fd_limit(); - init_logger(&logger_pattern, Some(log_rotation_opt))?; + init_logger(&logger_pattern); Ok(()) } diff --git a/client/cli/src/error.rs b/client/cli/src/error.rs index f29b59ed1243e..f091354be154b 100644 --- a/client/cli/src/error.rs +++ b/client/cli/src/error.rs @@ -17,7 +17,6 @@ // along with this program. If not, see . //! Initialization errors. -use flexi_logger::FlexiLoggerError; /// Result type alias for the CLI. pub type Result = std::result::Result; @@ -33,8 +32,6 @@ pub enum Error { Service(sc_service::Error), /// Client error Client(sp_blockchain::Error), - /// Flexi Logger error - FlexiLogger(FlexiLoggerError), /// Input error #[from(ignore)] Input(String), @@ -68,7 +65,6 @@ impl std::error::Error for Error { Error::Cli(ref err) => Some(err), Error::Service(ref err) => Some(err), Error::Client(ref err) => Some(err), - Error::FlexiLogger(ref err) => Some(err), Error::Input(_) => None, Error::InvalidListenMultiaddress => None, Error::Other(_) => None, diff --git a/client/cli/src/lib.rs b/client/cli/src/lib.rs index a06e48626f415..c7f48d2721468 100644 --- a/client/cli/src/lib.rs +++ b/client/cli/src/lib.rs @@ -27,13 +27,15 @@ mod config; mod error; mod params; mod runner; -mod logger; pub use arg_enums::*; pub use commands::*; pub use config::*; pub use error::*; +use lazy_static::lazy_static; +use log::info; pub use params::*; +use regex::Regex; pub use runner::*; use sc_service::{Configuration, TaskExecutor}; pub use sc_service::{ChainSpec, Role}; @@ -44,7 +46,6 @@ use structopt::{ clap::{self, AppSettings}, StructOpt, }; -pub use crate::logger::{init_logger, LogRotationOpt}; /// Substrate client CLI /// @@ -226,3 +227,79 @@ pub trait SubstrateCli: Sized { /// Native runtime version. fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion; } + +/// Initialize the logger +pub fn init_logger(pattern: &str) { + use ansi_term::Colour; + + let mut builder = env_logger::Builder::new(); + // Disable info logging by default for some modules: + builder.filter(Some("ws"), log::LevelFilter::Off); + builder.filter(Some("yamux"), log::LevelFilter::Off); + builder.filter(Some("hyper"), log::LevelFilter::Warn); + builder.filter(Some("cranelift_wasm"), log::LevelFilter::Warn); + // Always log the special target `sc_tracing`, overrides global level + builder.filter(Some("sc_tracing"), log::LevelFilter::Info); + // Enable info for others. + builder.filter(None, log::LevelFilter::Info); + + if let Ok(lvl) = std::env::var("RUST_LOG") { + builder.parse_filters(&lvl); + } + + builder.parse_filters(pattern); + let isatty = atty::is(atty::Stream::Stderr); + let enable_color = isatty; + + builder.format(move |buf, record| { + let now = time::now(); + let timestamp = + time::strftime("%Y-%m-%d %H:%M:%S", &now).expect("Error formatting log timestamp"); + + let mut output = if log::max_level() <= log::LevelFilter::Info { + format!( + "{} {}", + Colour::Black.bold().paint(timestamp), + record.args(), + ) + } else { + let name = ::std::thread::current() + .name() + .map_or_else(Default::default, |x| { + format!("{}", Colour::Blue.bold().paint(x)) + }); + let millis = (now.tm_nsec as f32 / 1000000.0).floor() as usize; + let timestamp = format!("{}.{:03}", timestamp, millis); + format!( + "{} {} {} {} {}", + Colour::Black.bold().paint(timestamp), + name, + record.level(), + record.target(), + record.args() + ) + }; + + if !isatty && record.level() <= log::Level::Info && atty::is(atty::Stream::Stdout) { + // duplicate INFO/WARN output to console + println!("{}", output); + } + + if !enable_color { + output = kill_color(output.as_ref()); + } + + writeln!(buf, "{}", output) + }); + + if builder.try_init().is_err() { + info!("💬 Not registering Substrate logger, as there is already a global logger registered!"); + } +} + +fn kill_color(s: &str) -> String { + lazy_static! { + static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").expect("Error initializing color regex"); + } + RE.replace_all(s, "").to_string() +} diff --git a/client/cli/src/params/shared_params.rs b/client/cli/src/params/shared_params.rs index 42e68757190e2..ad9ab04070563 100644 --- a/client/cli/src/params/shared_params.rs +++ b/client/cli/src/params/shared_params.rs @@ -19,10 +19,8 @@ use sc_service::config::BasePath; use std::path::PathBuf; use structopt::StructOpt; -use crate::logger::LogRotationOpt; /// Shared parameters used by all `CoreParams`. -#[allow(missing_docs)] #[derive(Debug, StructOpt)] pub struct SharedParams { /// Specify the chain specification (one of dev, local, or staging). @@ -43,9 +41,6 @@ pub struct SharedParams { /// By default, all targets log `info`. The global log level can be set with -l. #[structopt(short = "l", long, value_name = "LOG_PATTERN")] pub log: Vec, - - #[structopt(flatten)] - pub log_rotation_opt: LogRotationOpt, } impl SharedParams { @@ -77,9 +72,4 @@ impl SharedParams { pub fn log_filters(&self) -> &[String] { &self.log } - - /// Get the file rotation options for the logging - pub fn log_rotation_opt(&self) -> &LogRotationOpt { - &self.log_rotation_opt - } }