From 97d1a81b7c1e05b3a8d0f91af52e35377bb65296 Mon Sep 17 00:00:00 2001 From: teor Date: Tue, 1 Dec 2020 11:08:55 +1000 Subject: [PATCH] Automatically disable colors when tracing to a file --- Cargo.lock | 1 + zebrad/Cargo.toml | 1 + zebrad/src/components/tracing/component.rs | 5 ++++- zebrad/src/config.rs | 6 +++++- 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 97397db9..f8ad6ff6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3555,6 +3555,7 @@ name = "zebrad" version = "3.0.0-alpha.0" dependencies = [ "abscissa_core", + "atty", "chrono", "color-eyre", "dirs", diff --git a/zebrad/Cargo.toml b/zebrad/Cargo.toml index eb022121..04cb210f 100644 --- a/zebrad/Cargo.toml +++ b/zebrad/Cargo.toml @@ -39,6 +39,7 @@ metrics-exporter-prometheus = "0.1.0-alpha.10" dirs = "3.0.1" inferno = { version = "0.10.2", default-features = false } +atty = "0.2.14" [build-dependencies] vergen = "3.1.0" diff --git a/zebrad/src/components/tracing/component.rs b/zebrad/src/components/tracing/component.rs index 491dba73..e6f94448 100644 --- a/zebrad/src/components/tracing/component.rs +++ b/zebrad/src/components/tracing/component.rs @@ -21,9 +21,12 @@ impl Tracing { let filter = config.filter.unwrap_or_else(|| "".to_string()); let flame_root = &config.flamegraph; + // Only use color if tracing output is being sent to a terminal + let use_color = config.use_color && atty::is(atty::Stream::Stdout); + // Construct a tracing subscriber with the supplied filter and enable reloading. let builder = FmtSubscriber::builder() - .with_ansi(config.use_color) + .with_ansi(use_color) .with_env_filter(filter) .with_filter_reloading(); let filter_handle = builder.reload_handle(); diff --git a/zebrad/src/config.rs b/zebrad/src/config.rs index a0d2b517..d836be15 100644 --- a/zebrad/src/config.rs +++ b/zebrad/src/config.rs @@ -45,7 +45,11 @@ pub struct ZebradConfig { pub struct TracingSection { /// Whether to use colored terminal output, if available. /// - /// Defaults to `true`. + /// Colored terminal output is automatically disabled if an output stream + /// is connected to a file. (Or another non-terminal device.) + /// + /// Defaults to `true`, which automatically enables colored output to + /// terminals. pub use_color: bool, /// The filter used for tracing events.