Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add flag to CLI to disable colour coding of console output #4033

Merged
merged 5 commits into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 41 additions & 3 deletions bin/reth/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ use crate::{
stage, test_vectors,
version::{LONG_VERSION, SHORT_VERSION},
};
use clap::{ArgAction, Args, Parser, Subcommand};
use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum};
use reth_primitives::ChainSpec;
use reth_tracing::{
tracing::{metadata::LevelFilter, Level, Subscriber},
tracing_subscriber::{filter::Directive, registry::LookupSpan, EnvFilter},
BoxedLayer, FileWorkerGuard,
};
use std::sync::Arc;
use std::{fmt, fmt::Display, sync::Arc};

pub mod ext;

Expand Down Expand Up @@ -84,7 +84,8 @@ impl<Ext: RethCliExt> Cli<Ext> {
/// If file logging is enabled, this function returns a guard that must be kept alive to ensure
/// that all logs are flushed to disk.
pub fn init_tracing(&self) -> eyre::Result<Option<FileWorkerGuard>> {
let mut layers = vec![reth_tracing::stdout(self.verbosity.directive())];
let mut layers =
vec![reth_tracing::stdout(self.verbosity.directive(), &self.logs.color.to_string())];
let guard = self.logs.layer()?.map(|(layer, guard)| {
layers.push(layer);
guard
Expand Down Expand Up @@ -158,6 +159,16 @@ pub struct Logs {
/// The filter to use for logs written to the log file.
#[arg(long = "log.filter", value_name = "FILTER", global = true, default_value = "error")]
filter: String,

/// Sets whether or not the formatter emits ANSI terminal escape codes for colors and other
/// text formatting.
#[arg(
long,
value_name = "COLOR",
global = true,
default_value_t = ColorMode::Always
)]
color: ColorMode,
}

impl Logs {
Expand Down Expand Up @@ -219,11 +230,38 @@ impl Verbosity {
}
}

/// The color mode for the cli.
#[derive(Debug, Copy, Clone, ValueEnum, Eq, PartialEq)]
pub enum ColorMode {
/// Colors on
Always,
/// Colors on
Auto,
/// Colors off
Never,
}

impl Display for ColorMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ColorMode::Always => write!(f, "always"),
ColorMode::Auto => write!(f, "auto"),
ColorMode::Never => write!(f, "never"),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;

#[test]
fn parse_color_mode() {
let reth = Cli::<()>::try_parse_from(["reth", "node", "--color", "always"]).unwrap();
assert_eq!(reth.logs.color, ColorMode::Always);
}

/// Tests that the help message is parsed correctly. This ensures that clap args are configured
/// correctly and no conflicts are introduced via attributes that would result in a panic at
/// runtime
Expand Down
5 changes: 3 additions & 2 deletions crates/tracing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ pub fn init(layers: Vec<BoxedLayer<Registry>>) {
///
/// Colors can be disabled with `RUST_LOG_STYLE=never`, and event targets can be displayed with
/// `RUST_LOG_TARGET=1`.
pub fn stdout<S>(default_directive: impl Into<Directive>) -> BoxedLayer<S>
pub fn stdout<S>(default_directive: impl Into<Directive>, color: &str) -> BoxedLayer<S>
where
S: Subscriber,
for<'a> S: LookupSpan<'a>,
{
// TODO: Auto-detect
let with_ansi = std::env::var("RUST_LOG_STYLE").map(|val| val != "never").unwrap_or(true);
let with_ansi =
std::env::var("RUST_LOG_STYLE").map(|val| val != "never").unwrap_or(color != "never");
let with_target = std::env::var("RUST_LOG_TARGET").map(|val| val != "0").unwrap_or(true);

let filter =
Expand Down
Loading