Skip to content

Commit f0799e2

Browse files
authored
fix(logging): only color console logs on a terminal (#5616)
tracing-subscriber's formatter enables ANSI unless NO_COLOR is set and does no terminal detection, so the gateway, compute drivers, credential drivers, and certgen wrote escape codes into container logs collected by GKE and other log pipelines. Move the CLI's automatic color rules (NO_COLOR, FORCE_COLOR, terminal plus TERM capability) into openshell_core::color and pass the result to with_ansi in every long-running binary's console layer. The CLI keeps --color always|never and delegates its auto branch to the shared helper. Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com>
1 parent e8ba30f commit f0799e2

14 files changed

Lines changed: 186 additions & 65 deletions

File tree

‎crates/openshell-cli/src/color.rs‎

Lines changed: 12 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,19 @@ pub fn init(choice: ColorChoice) {
104104
choice,
105105
no_color.as_deref(),
106106
force_color.as_deref(),
107-
terminal_supports_ansi(std::io::stdout().is_terminal(), term.as_deref()),
107+
openshell_core::color::terminal_supports_ansi(
108+
std::io::stdout().is_terminal(),
109+
term.as_deref(),
110+
),
108111
);
109112
let stderr_enabled = resolve(
110113
choice,
111114
no_color.as_deref(),
112115
force_color.as_deref(),
113-
terminal_supports_ansi(std::io::stderr().is_terminal(), term.as_deref()),
116+
openshell_core::color::terminal_supports_ansi(
117+
std::io::stderr().is_terminal(),
118+
term.as_deref(),
119+
),
114120
);
115121
STDOUT_ENABLED.store(stdout_enabled, Ordering::Relaxed);
116122
STDERR_ENABLED.store(stderr_enabled, Ordering::Relaxed);
@@ -176,54 +182,9 @@ fn resolve(
176182
ColorChoice::Auto => {}
177183
}
178184

179-
// Both conventions key on presence rather than value: set and non-empty
180-
// means yes, regardless of what the value is. <https://no-color.org> and
181-
// <https://force-color.org>.
182-
if is_set(no_color) {
183-
return false;
184-
}
185-
if is_set(force_color) {
186-
return true;
187-
}
188-
189-
// Only `auto` consults the terminal. An explicit request above has already
190-
// returned, so `--color always` and `FORCE_COLOR` still win on a terminal
191-
// that reports no ANSI support.
192-
stream_supports_ansi
193-
}
194-
195-
/// Whether this output stream's terminal renders ANSI escapes.
196-
///
197-
/// Being attached to a terminal is not the same as that terminal rendering
198-
/// ANSI. `TERM` is the unix signal for it; Windows consoles enable virtual
199-
/// terminal processing instead and do not set `TERM`, so the check does not
200-
/// apply there.
201-
fn terminal_supports_ansi(stream_is_terminal: bool, term: Option<&OsStr>) -> bool {
202-
stream_is_terminal
203-
&& if cfg!(unix) {
204-
term_supports_ansi(term)
205-
} else {
206-
true
207-
}
208-
}
209-
210-
/// Whether the terminal named by `TERM` renders ANSI escapes on Unix.
211-
///
212-
/// Follows the rule `console` applies on unix, which this module overrides:
213-
/// `dumb` means no, and an unset `TERM` means no because nothing identifies a
214-
/// capable terminal.
215-
///
216-
/// Empty is treated as unset, which is a deliberate divergence: `console` reads
217-
/// `TERM=""` as `Ok("")`, and since that is not `"dumb"` it counts as capable.
218-
/// An empty value names no terminal type, and every other variable here already
219-
/// treats empty as unset, so it is handled the same way.
220-
fn term_supports_ansi(term: Option<&OsStr>) -> bool {
221-
is_set(term) && term != Some(OsStr::new("dumb"))
222-
}
223-
224-
/// Whether an environment variable counts as set: present and not empty.
225-
fn is_set(value: Option<&OsStr>) -> bool {
226-
value.is_some_and(|value| !value.is_empty())
185+
// Only `auto` consults the environment and the terminal, so `--color
186+
// always|never` above wins over both.
187+
openshell_core::color::auto(no_color, force_color, stream_supports_ansi)
227188
}
228189

229190
/// A value tagged with a style, rendered only when color is enabled.
@@ -370,7 +331,7 @@ mod tests {
370331
// and make every `.green()` below ambiguous.
371332
use super::{
372333
ColorChoice, Colorize, Ordering, STDERR_ENABLED, STDOUT_ENABLED, Style, painted_enabled,
373-
resolve, term_supports_ansi,
334+
resolve,
374335
};
375336
use std::ffi::OsStr;
376337

@@ -541,19 +502,6 @@ mod tests {
541502
assert!(!resolve(ColorChoice::Auto, None, Some(env("")), false));
542503
}
543504

544-
#[test]
545-
fn term_capability_follows_the_console_rule() {
546-
assert!(term_supports_ansi(Some(OsStr::new("xterm-256color"))));
547-
assert!(term_supports_ansi(Some(OsStr::new("screen"))));
548-
assert!(!term_supports_ansi(Some(OsStr::new("dumb"))));
549-
// Nothing to suggest a capable terminal, so assume none.
550-
assert!(!term_supports_ansi(None));
551-
// Empty names no terminal type; treated as unset, unlike `console`.
552-
assert!(!term_supports_ansi(Some(OsStr::new(""))));
553-
// Only an exact match counts; `dumb-something` is a different terminal.
554-
assert!(term_supports_ansi(Some(OsStr::new("dumb-but-color"))));
555-
}
556-
557505
#[test]
558506
fn auto_does_not_style_an_incapable_terminal() {
559507
// A `dumb` terminal is still a terminal, so `is_terminal()` alone would

‎crates/openshell-core/src/color.rs‎

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
//! Automatic ANSI color detection for console output.
5+
//!
6+
//! `tracing_subscriber`'s formatter turns ANSI on unless `NO_COLOR` is set. It
7+
//! does not check whether the output stream is a terminal, so a gateway or
8+
//! driver running in a container writes escape sequences into its collected
9+
//! logs. Long-running binaries pass [`stdout_ansi`] or [`stderr_ansi`] to
10+
//! `with_ansi` so console logs are colored only on a terminal that can render
11+
//! them.
12+
//!
13+
//! Resolution order, highest precedence first:
14+
//!
15+
//! 1. `NO_COLOR`, set and non-empty, disables color (<https://no-color.org>).
16+
//! 2. `FORCE_COLOR`, set and non-empty, forces color on (<https://force-color.org>).
17+
//! 3. Otherwise the stream is colored only when it is a terminal *and* that
18+
//! terminal renders ANSI.
19+
20+
use std::ffi::OsStr;
21+
use std::io::IsTerminal;
22+
23+
/// Whether console output written to stdout should carry ANSI escapes.
24+
#[must_use]
25+
pub fn stdout_ansi() -> bool {
26+
stream_ansi(std::io::stdout().is_terminal())
27+
}
28+
29+
/// Whether console output written to stderr should carry ANSI escapes.
30+
#[must_use]
31+
pub fn stderr_ansi() -> bool {
32+
stream_ansi(std::io::stderr().is_terminal())
33+
}
34+
35+
fn stream_ansi(stream_is_terminal: bool) -> bool {
36+
let term = std::env::var_os("TERM");
37+
auto(
38+
std::env::var_os("NO_COLOR").as_deref(),
39+
std::env::var_os("FORCE_COLOR").as_deref(),
40+
terminal_supports_ansi(stream_is_terminal, term.as_deref()),
41+
)
42+
}
43+
44+
/// Decide whether one stream may carry escapes when no explicit color choice
45+
/// was made. Pure so the precedence rules are testable without process state.
46+
#[must_use]
47+
pub fn auto(
48+
no_color: Option<&OsStr>,
49+
force_color: Option<&OsStr>,
50+
stream_supports_ansi: bool,
51+
) -> bool {
52+
// Both conventions key on presence rather than value: set and non-empty
53+
// means yes, regardless of what the value is.
54+
if is_set(no_color) {
55+
return false;
56+
}
57+
if is_set(force_color) {
58+
return true;
59+
}
60+
stream_supports_ansi
61+
}
62+
63+
/// Whether this output stream's terminal renders ANSI escapes.
64+
///
65+
/// Being attached to a terminal is not the same as that terminal rendering
66+
/// ANSI. `TERM` is the unix signal for it; Windows consoles enable virtual
67+
/// terminal processing instead and do not set `TERM`, so the check does not
68+
/// apply there.
69+
#[must_use]
70+
pub fn terminal_supports_ansi(stream_is_terminal: bool, term: Option<&OsStr>) -> bool {
71+
stream_is_terminal
72+
&& if cfg!(unix) {
73+
term_supports_ansi(term)
74+
} else {
75+
true
76+
}
77+
}
78+
79+
/// Whether the terminal named by `TERM` renders ANSI escapes on Unix.
80+
///
81+
/// Follows the rule `console` applies on unix: `dumb` means no, and an unset
82+
/// `TERM` means no because nothing identifies a capable terminal.
83+
///
84+
/// Empty is treated as unset, which is a deliberate divergence: `console` reads
85+
/// `TERM=""` as `Ok("")`, and since that is not `"dumb"` it counts as capable.
86+
/// An empty value names no terminal type, and every other variable here already
87+
/// treats empty as unset, so it is handled the same way.
88+
fn term_supports_ansi(term: Option<&OsStr>) -> bool {
89+
is_set(term) && term != Some(OsStr::new("dumb"))
90+
}
91+
92+
/// Whether an environment variable counts as set: present and not empty.
93+
fn is_set(value: Option<&OsStr>) -> bool {
94+
value.is_some_and(|value| !value.is_empty())
95+
}
96+
97+
#[cfg(test)]
98+
mod tests {
99+
use super::*;
100+
101+
fn env(value: &str) -> &OsStr {
102+
OsStr::new(value)
103+
}
104+
105+
#[test]
106+
fn no_color_disables_when_set_and_non_empty() {
107+
assert!(!auto(Some(env("1")), None, true));
108+
// Presence is what counts; a value that reads as falsy still disables.
109+
assert!(!auto(Some(env("0")), None, true));
110+
// NO_COLOR outranks FORCE_COLOR.
111+
assert!(!auto(Some(env("1")), Some(env("1")), true));
112+
// An empty value is not "set" for the purposes of the convention.
113+
assert!(auto(Some(env("")), None, true));
114+
}
115+
116+
#[test]
117+
fn force_color_enables_when_set_and_non_empty() {
118+
assert!(auto(None, Some(env("1")), false));
119+
assert!(auto(None, Some(env("0")), false));
120+
assert!(!auto(None, Some(env("")), false));
121+
}
122+
123+
#[test]
124+
fn otherwise_follows_the_stream() {
125+
assert!(auto(None, None, true));
126+
// A container log stream is not a terminal, so it stays plain.
127+
assert!(!auto(None, None, false));
128+
}
129+
130+
#[test]
131+
fn redirected_stream_is_never_capable() {
132+
assert!(!terminal_supports_ansi(false, Some(env("xterm-256color"))));
133+
}
134+
135+
#[cfg(unix)]
136+
#[test]
137+
fn terminal_capability_follows_term() {
138+
assert!(terminal_supports_ansi(true, Some(env("xterm-256color"))));
139+
assert!(!terminal_supports_ansi(true, Some(env("dumb"))));
140+
assert!(!terminal_supports_ansi(true, None));
141+
}
142+
143+
#[test]
144+
fn term_capability_follows_the_console_rule() {
145+
assert!(term_supports_ansi(Some(env("xterm-256color"))));
146+
assert!(term_supports_ansi(Some(env("screen"))));
147+
assert!(!term_supports_ansi(Some(env("dumb"))));
148+
// Nothing to suggest a capable terminal, so assume none.
149+
assert!(!term_supports_ansi(None));
150+
// Empty names no terminal type; treated as unset, unlike `console`.
151+
assert!(!term_supports_ansi(Some(env(""))));
152+
// Only an exact match counts; `dumb-something` is a different terminal.
153+
assert!(term_supports_ansi(Some(env("dumb-but-color"))));
154+
}
155+
}

‎crates/openshell-core/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
pub mod activity;
1313
pub mod app_listener;
1414
pub mod auth;
15+
pub mod color;
1516
pub mod compute;
1617
pub mod config;
1718
pub mod container_paths;

‎crates/openshell-driver-docker/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ async fn main() -> Result<()> {
6666
gateway_name: args.gateway_name.as_deref(),
6767
service_version: VERSION,
6868
log_level: &args.log_level,
69+
ansi: openshell_core::color::stdout_ansi(),
6970
},
7071
);
7172
args.otlp.warn_deprecated();

‎crates/openshell-driver-kubernetes-secrets/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ struct Args {
3737
async fn main() -> Result<()> {
3838
let args = Args::parse();
3939
tracing_subscriber::fmt()
40+
.with_ansi(openshell_core::color::stdout_ansi())
4041
.with_env_filter(
4142
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&args.log_level)),
4243
)

‎crates/openshell-driver-kubernetes/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ async fn main() -> Result<()> {
242242
gateway_name: args.gateway_name.as_deref(),
243243
service_version: VERSION,
244244
log_level: &args.log_level,
245+
ansi: openshell_core::color::stdout_ansi(),
245246
},
246247
);
247248
args.otlp.warn_deprecated();

‎crates/openshell-driver-podman/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ async fn main() -> Result<()> {
217217
gateway_name: args.gateway_name.as_deref(),
218218
service_version: VERSION,
219219
log_level: &args.log_level,
220+
ansi: openshell_core::color::stdout_ansi(),
220221
},
221222
);
222223
args.otlp.warn_deprecated();

‎crates/openshell-driver-vault/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ struct Args {
6262
async fn main() -> Result<()> {
6363
let args = Args::parse();
6464
tracing_subscriber::fmt()
65+
.with_ansi(openshell_core::color::stdout_ansi())
6566
.with_env_filter(
6667
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&args.log_level)),
6768
)

‎crates/openshell-driver-vm/src/driver.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5201,6 +5201,7 @@ pub async fn run_image_preparation_worker(request_path: &Path) -> Result<(), Str
52015201
preparation::watch_parent(request.parent_pid)?;
52025202
tracing_subscriber::fmt()
52035203
.with_writer(std::io::stderr)
5204+
.with_ansi(openshell_core::color::stderr_ansi())
52045205
.with_env_filter(request.config.log_level.clone())
52055206
.try_init()
52065207
.map_err(|error| format!("initialize image preparation logging: {error}"))?;

‎crates/openshell-driver-vm/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,7 @@ async fn main() -> Result<()> {
304304
gateway_name: args.gateway_name.as_deref(),
305305
service_version: VERSION,
306306
log_level: &args.log_level,
307+
ansi: openshell_core::color::stdout_ansi(),
307308
},
308309
);
309310
args.otlp.warn_deprecated();

0 commit comments

Comments
 (0)