Skip to content

Commit 90495b3

Browse files
authored
Enable coloring in console log (rust-lang#528)
* Enable feat ansi of dep tracing-subscriber * Rm use of `tracing_appender::non_blocking` since `cargo-binstall` is so simple that it doesn't need it. * Use `tracing::{error, info}` in `MainExit::report` * Use `tracing::{error, warn}` in `BinstallError::report` * Add dep supports-color v1.3.1 to crates/bin * Enable ansi of `tracing_subscriber::fmt` if stdout supports it Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
1 parent 4e87587 commit 90495b3

File tree

6 files changed

+51
-77
lines changed

6 files changed

+51
-77
lines changed

Cargo.lock

+20-44
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/bin/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,13 @@ miette = "5.4.1"
3131
mimalloc = { version = "0.1.31", default-features = false, optional = true }
3232
once_cell = "1.16.0"
3333
semver = "1.0.14"
34+
supports-color = "1.3.1"
3435
tempfile = "3.3.0"
3536
tokio = { version = "1.21.2", features = ["rt-multi-thread"], default-features = false }
3637
tracing-core = "0.1.30"
3738
tracing = { version = "0.1.37", default-features = false }
3839
tracing-log = { version = "0.1.3", default-features = false }
39-
tracing-appender = "0.2.2"
40-
tracing-subscriber = { version = "0.3.16", features = ["fmt", "json"], default-features = false }
40+
tracing-subscriber = { version = "0.3.16", features = ["fmt", "json", "ansi"], default-features = false }
4141

4242
[build-dependencies]
4343
embed-resource = "1.7.4"

crates/bin/src/bin_util.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::{
22
future::Future,
3-
io::{self, Write},
43
process::{ExitCode, Termination},
54
time::Duration,
65
};
@@ -9,6 +8,7 @@ use binstalk::errors::BinstallError;
98
use binstalk::helpers::{signal::cancel_on_user_sig_term, tasks::AutoAbortJoinHandle};
109
use miette::Result;
1110
use tokio::runtime::Runtime;
11+
use tracing::{error, info};
1212

1313
pub enum MainExit {
1414
Success(Option<Duration>),
@@ -21,13 +21,13 @@ impl Termination for MainExit {
2121
match self {
2222
Self::Success(spent) => {
2323
if let Some(spent) = spent {
24-
writeln!(io::stdout(), "Done in {spent:?}").ok();
24+
info!("Done in {spent:?}");
2525
}
2626
ExitCode::SUCCESS
2727
}
2828
Self::Error(err) => err.report(),
2929
Self::Report(err) => {
30-
writeln!(io::stderr(), "Fatal error:\n{err:?}").ok();
30+
error!("Fatal error:\n{err:?}");
3131
ExitCode::from(16)
3232
}
3333
}

crates/bin/src/logging.rs

+21-24
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
use std::{cmp::min, io, iter::repeat};
1+
use std::{cmp::min, iter::repeat};
22

33
use log::{LevelFilter, Log, STATIC_MAX_LEVEL};
44
use once_cell::sync::Lazy;
5+
use supports_color::{on as supports_color_on_stream, Stream::Stdout};
56
use tracing::{
67
callsite::Callsite,
78
dispatcher, field,
89
subscriber::{self, set_global_default},
910
Event, Level, Metadata,
1011
};
11-
use tracing_appender::non_blocking::{NonBlockingBuilder, WorkerGuard};
1212
use tracing_core::{identify_callsite, metadata::Kind, subscriber::Subscriber};
1313
use tracing_log::AsTrace;
1414
use tracing_subscriber::{filter::targets::Targets, fmt::fmt, layer::SubscriberExt};
@@ -131,7 +131,7 @@ impl Log for Logger {
131131
fn flush(&self) {}
132132
}
133133

134-
pub fn logging(args: &Args) -> WorkerGuard {
134+
pub fn logging(args: &Args) {
135135
// Calculate log_level
136136
let log_level = min(args.log_level, STATIC_MAX_LEVEL);
137137

@@ -141,31 +141,30 @@ pub fn logging(args: &Args) -> WorkerGuard {
141141
// Forward log to tracing
142142
Logger::init(log_level);
143143

144-
// Setup non-blocking stdout
145-
let (non_blocking, guard) = NonBlockingBuilder::default()
146-
.lossy(false)
147-
.finish(io::stdout());
148-
149144
// Build fmt subscriber
150145
let log_level = log_level.as_trace();
151-
let subscriber_builder = fmt().with_writer(non_blocking).with_max_level(log_level);
146+
let subscriber_builder = fmt().with_max_level(log_level);
152147

153148
let subscriber: Box<dyn Subscriber + Send + Sync> = if args.json_output {
154149
Box::new(subscriber_builder.json().finish())
155150
} else {
156-
Box::new(
157-
subscriber_builder
158-
.compact()
159-
// Disable time, target, file, line_num, thread name/ids to make the
160-
// output more readable
161-
.without_time()
162-
.with_target(false)
163-
.with_file(false)
164-
.with_line_number(false)
165-
.with_thread_names(false)
166-
.with_thread_ids(false)
167-
.finish(),
168-
)
151+
// Disable time, target, file, line_num, thread name/ids to make the
152+
// output more readable
153+
let subscriber_builder = subscriber_builder
154+
.without_time()
155+
.with_target(false)
156+
.with_file(false)
157+
.with_line_number(false)
158+
.with_thread_names(false)
159+
.with_thread_ids(false);
160+
161+
// subscriber_builder defaults to write to io::stdout(),
162+
// so tests whether it supports color.
163+
let stdout_supports_color = supports_color_on_stream(Stdout)
164+
.map(|color_level| color_level.has_basic)
165+
.unwrap_or_default();
166+
167+
Box::new(subscriber_builder.with_ansi(stdout_supports_color).finish())
169168
};
170169

171170
// Builder layer for filtering
@@ -178,6 +177,4 @@ pub fn logging(args: &Args) -> WorkerGuard {
178177

179178
// Setup global subscriber
180179
set_global_default(subscriber).unwrap();
181-
182-
guard
183180
}

crates/bin/src/main.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ fn main() -> MainExit {
2727
println!("{}", env!("CARGO_PKG_VERSION"));
2828
MainExit::Success(None)
2929
} else {
30-
let _guard = logging(&args);
30+
logging(&args);
3131

3232
let start = Instant::now();
3333

crates/binstalk/src/errors.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::{
2-
io::{self, Write},
2+
io,
33
path::PathBuf,
44
process::{ExitCode, ExitStatus, Termination},
55
};
@@ -12,6 +12,7 @@ use compact_str::CompactString;
1212
use miette::{Diagnostic, Report};
1313
use thiserror::Error;
1414
use tokio::task;
15+
use tracing::{error, warn};
1516

1617
/// Error kinds emitted by cargo-binstall.
1718
#[derive(Error, Diagnostic, Debug)]
@@ -399,9 +400,9 @@ impl Termination for BinstallError {
399400
fn report(self) -> ExitCode {
400401
let code = self.exit_code();
401402
if let BinstallError::UserAbort = self {
402-
writeln!(io::stdout(), "Installation cancelled").ok();
403+
warn!("Installation cancelled");
403404
} else {
404-
writeln!(io::stderr(), "Fatal error:\n{:?}", Report::new(self)).ok();
405+
error!("Fatal error:\n{:?}", Report::new(self));
405406
}
406407

407408
code

0 commit comments

Comments
 (0)