Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
Revert "Add log rotation (#6564)" (#6627)
Browse files Browse the repository at this point in the history
This reverts commit 802a0d0.
  • Loading branch information
bkchr authored Jul 10, 2020
1 parent e68e3a3 commit 56cf04f
Show file tree
Hide file tree
Showing 7 changed files with 84 additions and 50 deletions.
22 changes: 1 addition & 21 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion bin/node/bench/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion client/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
13 changes: 2 additions & 11 deletions client/cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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<LogRotationOpt> {
Ok(self.shared_params().log_rotation_opt().clone())
}

/// Initialize substrate. This must be done only once.
///
/// This method:
Expand All @@ -505,12 +497,11 @@ pub trait CliConfiguration: Sized {
/// 3. Initialize the logger
fn init<C: SubstrateCli>(&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(())
}
Expand Down
4 changes: 0 additions & 4 deletions client/cli/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Initialization errors.
use flexi_logger::FlexiLoggerError;

/// Result type alias for the CLI.
pub type Result<T> = std::result::Result<T, Error>;
Expand All @@ -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),
Expand Down Expand Up @@ -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,
Expand Down
81 changes: 79 additions & 2 deletions client/cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -44,7 +46,6 @@ use structopt::{
clap::{self, AppSettings},
StructOpt,
};
pub use crate::logger::{init_logger, LogRotationOpt};

/// Substrate client CLI
///
Expand Down Expand Up @@ -226,3 +227,79 @@ pub trait SubstrateCli: Sized {
/// Native runtime version.
fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'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()
}
10 changes: 0 additions & 10 deletions client/cli/src/params/shared_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -43,9 +41,6 @@ pub struct SharedParams {
/// By default, all targets log `info`. The global log level can be set with -l<level>.
#[structopt(short = "l", long, value_name = "LOG_PATTERN")]
pub log: Vec<String>,

#[structopt(flatten)]
pub log_rotation_opt: LogRotationOpt,
}

impl SharedParams {
Expand Down Expand Up @@ -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
}
}

0 comments on commit 56cf04f

Please sign in to comment.