Skip to content

Commit

Permalink
Enable coloring in console log (rust-lang#528)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
NobodyXu authored Nov 13, 2022
1 parent 4e87587 commit 90495b3
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 77 deletions.
64 changes: 20 additions & 44 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions crates/bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ miette = "5.4.1"
mimalloc = { version = "0.1.31", default-features = false, optional = true }
once_cell = "1.16.0"
semver = "1.0.14"
supports-color = "1.3.1"
tempfile = "3.3.0"
tokio = { version = "1.21.2", features = ["rt-multi-thread"], default-features = false }
tracing-core = "0.1.30"
tracing = { version = "0.1.37", default-features = false }
tracing-log = { version = "0.1.3", default-features = false }
tracing-appender = "0.2.2"
tracing-subscriber = { version = "0.3.16", features = ["fmt", "json"], default-features = false }
tracing-subscriber = { version = "0.3.16", features = ["fmt", "json", "ansi"], default-features = false }

[build-dependencies]
embed-resource = "1.7.4"
Expand Down
6 changes: 3 additions & 3 deletions crates/bin/src/bin_util.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{
future::Future,
io::{self, Write},
process::{ExitCode, Termination},
time::Duration,
};
Expand All @@ -9,6 +8,7 @@ use binstalk::errors::BinstallError;
use binstalk::helpers::{signal::cancel_on_user_sig_term, tasks::AutoAbortJoinHandle};
use miette::Result;
use tokio::runtime::Runtime;
use tracing::{error, info};

pub enum MainExit {
Success(Option<Duration>),
Expand All @@ -21,13 +21,13 @@ impl Termination for MainExit {
match self {
Self::Success(spent) => {
if let Some(spent) = spent {
writeln!(io::stdout(), "Done in {spent:?}").ok();
info!("Done in {spent:?}");
}
ExitCode::SUCCESS
}
Self::Error(err) => err.report(),
Self::Report(err) => {
writeln!(io::stderr(), "Fatal error:\n{err:?}").ok();
error!("Fatal error:\n{err:?}");
ExitCode::from(16)
}
}
Expand Down
45 changes: 21 additions & 24 deletions crates/bin/src/logging.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use std::{cmp::min, io, iter::repeat};
use std::{cmp::min, iter::repeat};

use log::{LevelFilter, Log, STATIC_MAX_LEVEL};
use once_cell::sync::Lazy;
use supports_color::{on as supports_color_on_stream, Stream::Stdout};
use tracing::{
callsite::Callsite,
dispatcher, field,
subscriber::{self, set_global_default},
Event, Level, Metadata,
};
use tracing_appender::non_blocking::{NonBlockingBuilder, WorkerGuard};
use tracing_core::{identify_callsite, metadata::Kind, subscriber::Subscriber};
use tracing_log::AsTrace;
use tracing_subscriber::{filter::targets::Targets, fmt::fmt, layer::SubscriberExt};
Expand Down Expand Up @@ -131,7 +131,7 @@ impl Log for Logger {
fn flush(&self) {}
}

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

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

// Setup non-blocking stdout
let (non_blocking, guard) = NonBlockingBuilder::default()
.lossy(false)
.finish(io::stdout());

// Build fmt subscriber
let log_level = log_level.as_trace();
let subscriber_builder = fmt().with_writer(non_blocking).with_max_level(log_level);
let subscriber_builder = fmt().with_max_level(log_level);

let subscriber: Box<dyn Subscriber + Send + Sync> = if args.json_output {
Box::new(subscriber_builder.json().finish())
} else {
Box::new(
subscriber_builder
.compact()
// Disable time, target, file, line_num, thread name/ids to make the
// output more readable
.without_time()
.with_target(false)
.with_file(false)
.with_line_number(false)
.with_thread_names(false)
.with_thread_ids(false)
.finish(),
)
// Disable time, target, file, line_num, thread name/ids to make the
// output more readable
let subscriber_builder = subscriber_builder
.without_time()
.with_target(false)
.with_file(false)
.with_line_number(false)
.with_thread_names(false)
.with_thread_ids(false);

// subscriber_builder defaults to write to io::stdout(),
// so tests whether it supports color.
let stdout_supports_color = supports_color_on_stream(Stdout)
.map(|color_level| color_level.has_basic)
.unwrap_or_default();

Box::new(subscriber_builder.with_ansi(stdout_supports_color).finish())
};

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

// Setup global subscriber
set_global_default(subscriber).unwrap();

guard
}
2 changes: 1 addition & 1 deletion crates/bin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn main() -> MainExit {
println!("{}", env!("CARGO_PKG_VERSION"));
MainExit::Success(None)
} else {
let _guard = logging(&args);
logging(&args);

let start = Instant::now();

Expand Down
7 changes: 4 additions & 3 deletions crates/binstalk/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
io::{self, Write},
io,
path::PathBuf,
process::{ExitCode, ExitStatus, Termination},
};
Expand All @@ -12,6 +12,7 @@ use compact_str::CompactString;
use miette::{Diagnostic, Report};
use thiserror::Error;
use tokio::task;
use tracing::{error, warn};

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

code
Expand Down

0 comments on commit 90495b3

Please sign in to comment.