Skip to content

Commit

Permalink
Refactor to use console global ANSI style control
Browse files Browse the repository at this point in the history
  • Loading branch information
jasl committed Jul 20, 2024
1 parent 1c13aaf commit 2891d3f
Show file tree
Hide file tree
Showing 15 changed files with 43 additions and 213 deletions.
2 changes: 0 additions & 2 deletions bridges/relays/utils/src/initialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ pub fn initialize_logger(with_timestamp: bool) {
)
.expect("static format string is valid");

console::set_colors_enabled(true);

let mut builder = env_logger::Builder::new();
builder.filter_level(log::LevelFilter::Warn);
builder.filter_module("bridge", log::LevelFilter::Info);
Expand Down
1 change: 0 additions & 1 deletion cumulus/test/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -891,7 +891,6 @@ pub fn node_config(
announce_block: true,
data_path: root,
base_path,
informant_output_format: Default::default(),
wasm_runtime_overrides: None,
runtime_cache_size: 2,
})
Expand Down
1 change: 0 additions & 1 deletion polkadot/node/test/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,6 @@ pub fn node_config(
announce_block: true,
data_path: root,
base_path,
informant_output_format: Default::default(),
}
}

Expand Down
1 change: 0 additions & 1 deletion substrate/bin/node/cli/benches/block_production.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase {
announce_block: true,
data_path: base_path.path().into(),
base_path,
informant_output_format: Default::default(),
wasm_runtime_overrides: None,
};

Expand Down
1 change: 0 additions & 1 deletion substrate/bin/node/cli/benches/transaction_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase {
announce_block: true,
data_path: base_path.path().into(),
base_path,
informant_output_format: Default::default(),
wasm_runtime_overrides: None,
};

Expand Down
3 changes: 1 addition & 2 deletions substrate/client/cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use names::{Generator, Name};
use sc_service::{
config::{
BasePath, Configuration, DatabaseSource, IpNetwork, KeystoreConfig, NetworkConfiguration,
NodeKeyConfig, OffchainWorkerConfig, OutputFormat, PrometheusConfig, PruningMode, Role,
NodeKeyConfig, OffchainWorkerConfig, PrometheusConfig, PruningMode, Role,
RpcBatchRequestConfig, RpcMethods, TelemetryEndpoints, TransactionPoolOptions,
WasmExecutionMethod,
},
Expand Down Expand Up @@ -550,7 +550,6 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
announce_block: self.announce_block()?,
role,
base_path,
informant_output_format: OutputFormat { enable_color: !self.disable_log_color()? },
runtime_cache_size,
})
}
Expand Down
1 change: 0 additions & 1 deletion substrate/client/cli/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,6 @@ mod tests {
announce_block: true,
base_path: sc_service::BasePath::new(root.clone()),
data_path: root,
informant_output_format: Default::default(),
runtime_cache_size: 2,
},
runtime,
Expand Down
20 changes: 8 additions & 12 deletions substrate/client/informant/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::OutputFormat;
use console::{Attribute, Color};
use console::style;
use log::info;
use sc_client_api::ClientInfo;
use sc_network::NetworkStatus;
Expand Down Expand Up @@ -47,19 +46,16 @@ pub struct InformantDisplay<B: BlockT> {
last_total_bytes_inbound: u64,
/// The last seen total of bytes sent.
last_total_bytes_outbound: u64,
/// The format to print output in.
format: OutputFormat,
}

impl<B: BlockT> InformantDisplay<B> {
/// Builds a new informant display system.
pub fn new(format: OutputFormat) -> InformantDisplay<B> {
pub fn new() -> InformantDisplay<B> {
InformantDisplay {
last_number: None,
last_update: Instant::now(),
last_total_bytes_inbound: 0,
last_total_bytes_outbound: 0,
format,
}
}

Expand Down Expand Up @@ -146,15 +142,15 @@ impl<B: BlockT> InformantDisplay<B> {
target: "substrate",
"{} {}{} ({} peers), best: #{} ({}), finalized #{} ({}), {} {}",
level,
self.format.print(Color::White, Some(Attribute::Bold), &status),
style(&status).white().bold().to_string(),
target,
self.format.print(Color::White, Some(Attribute::Bold), format!("{}", num_connected_peers)),
self.format.print(Color::White, Some(Attribute::Bold), format!("{}", best_number)),
style(format!("{}", num_connected_peers)).white().bold().to_string(),
style(format!("{}", best_number)).white().bold().to_string(),
best_hash,
self.format.print(Color::White, Some(Attribute::Bold), format!("{}", finalized_number)),
style(format!("{}", finalized_number)).white().bold().to_string(),
info.chain.finalized_hash,
self.format.print(Color::Green, None, format!("⬇ {}", TransferRateFormat(avg_bytes_per_sec_inbound))),
self.format.print(Color::Red, None, format!("⬆ {}", TransferRateFormat(avg_bytes_per_sec_outbound))),
style(format!("⬇ {}", TransferRateFormat(avg_bytes_per_sec_inbound))).green().to_string(),
style(format!("⬆ {}", TransferRateFormat(avg_bytes_per_sec_outbound))).red().to_string(),
)
}
}
Expand Down
51 changes: 9 additions & 42 deletions substrate/client/informant/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

//! Console informant. Prints sync progress and block events. Runs on the calling thread.
use console::{style, Attribute, Color};
use console::style;
use futures::prelude::*;
use futures_timer::Delay;
use log::{debug, info, trace};
Expand All @@ -36,45 +36,15 @@ fn interval(duration: Duration) -> impl Stream<Item = ()> + Unpin {
futures::stream::unfold((), move |_| Delay::new(duration).map(|_| Some(((), ())))).map(drop)
}

/// The format to print telemetry output in.
#[derive(Clone, Debug)]
pub struct OutputFormat {
/// Enable color output in logs.
///
/// Is enabled by default.
pub enable_color: bool,
}

impl Default for OutputFormat {
fn default() -> Self {
Self { enable_color: true }
}
}

impl OutputFormat {
/// Print with color if `self.enable_color == true`.
fn print(&self, color: Color, attr: Option<Attribute>, data: impl Display) -> impl Display {
if self.enable_color {
let mut styled = style(data).fg(color);
if let Some(attr) = attr {
styled = styled.attr(attr);
}
styled.to_string()
} else {
data.to_string()
}
}
}

/// Builds the informant and returns a `Future` that drives the informant.
pub async fn build<B: BlockT, C, N, S>(client: Arc<C>, network: N, syncing: S, format: OutputFormat)
pub async fn build<B: BlockT, C, N, S>(client: Arc<C>, network: N, syncing: S)
where
N: NetworkStatusProvider,
S: SyncStatusProvider<B>,
C: UsageProvider<B> + HeaderMetadata<B> + BlockchainEvents<B>,
<C as HeaderMetadata<B>>::Error: Display,
{
let mut display = display::InformantDisplay::new(format.clone());
let mut display = display::InformantDisplay::new();

let client_1 = client.clone();

Expand Down Expand Up @@ -104,14 +74,11 @@ where

futures::select! {
() = display_notifications.fuse() => (),
() = display_block_import(client, format).fuse() => (),
() = display_block_import(client).fuse() => (),
};
}

fn display_block_import<B: BlockT, C>(
client: Arc<C>,
format: OutputFormat,
) -> impl Future<Output = ()>
fn display_block_import<B: BlockT, C>(client: Arc<C>) -> impl Future<Output = ()>
where
C: UsageProvider<B> + HeaderMetadata<B> + BlockchainEvents<B>,
<C as HeaderMetadata<B>>::Error: Display,
Expand All @@ -135,11 +102,11 @@ where
match maybe_ancestor {
Ok(ref ancestor) if ancestor.hash != *last_hash => info!(
"♻️ Reorg on #{},{} to #{},{}, common ancestor #{},{}",
format.print(Color::Red, Some(Attribute::Bold), last_num),
style(last_num).red().bold().to_string(),
last_hash,
format.print(Color::Green, Some(Attribute::Bold), n.header.number()),
style(n.header.number()).green().bold().to_string(),
n.hash,
format.print(Color::White, Some(Attribute::Bold), ancestor.number),
style(ancestor.number).white().bold().to_string(),
ancestor.hash,
),
Ok(_) => {},
Expand All @@ -165,7 +132,7 @@ where
info!(
target: "substrate",
"{best_indicator} Imported #{} ({} → {})",
format.print(Color::White, Some(Attribute::Bold), n.header.number()),
style(n.header.number()).white().bold().to_string(),
n.header.parent_hash(),
n.hash,
);
Expand Down
7 changes: 1 addition & 6 deletions substrate/client/service/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,12 +514,7 @@ where
spawn_handle.spawn(
"informant",
None,
sc_informant::build(
client.clone(),
network,
sync_service.clone(),
config.informant_output_format,
),
sc_informant::build(client.clone(), network, sync_service.clone()),
);

task_manager.keep_alive((config.base_path, rpc));
Expand Down
3 changes: 0 additions & 3 deletions substrate/client/service/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use prometheus_endpoint::Registry;
use sc_chain_spec::ChainSpec;
pub use sc_client_db::{BlocksPruning, Database, DatabaseSource, PruningMode};
pub use sc_executor::{WasmExecutionMethod, WasmtimeInstantiationStrategy};
pub use sc_informant::OutputFormat;
pub use sc_network::{
config::{
MultiaddrWithPeerId, NetworkConfiguration, NodeKeyConfig, NonDefaultSetConfig, ProtocolId,
Expand Down Expand Up @@ -146,8 +145,6 @@ pub struct Configuration {
pub data_path: PathBuf,
/// Base path of the configuration. This is shared between chains.
pub base_path: BasePath,
/// Configuration of the output format that the informant uses.
pub informant_output_format: OutputFormat,
/// Maximum number of different runtime versions that can be cached.
pub runtime_cache_size: u8,
}
Expand Down
1 change: 0 additions & 1 deletion substrate/client/service/test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,6 @@ fn node_config<E: ChainSpecExtension + Clone + 'static + Send + Sync>(
announce_block: true,
base_path: BasePath::new(root.clone()),
data_path: root,
informant_output_format: Default::default(),
runtime_cache_size: 2,
}
}
Expand Down
2 changes: 1 addition & 1 deletion substrate/client/tracing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ lazy_static = { workspace = true }
libc = { workspace = true }
log = { workspace = true, default-features = true }
parking_lot = { workspace = true, default-features = true }
regex = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true, default-features = true }
thiserror = { workspace = true }
Expand All @@ -42,6 +41,7 @@ sp-tracing = { workspace = true, default-features = true }

[dev-dependencies]
criterion = { workspace = true, default-features = true }
regex = { workspace = true }
tracing-subscriber = { workspace = true, features = ["chrono", "parking_lot"] }

[[bench]]
Expand Down
Loading

0 comments on commit 2891d3f

Please sign in to comment.