Skip to content

Commit

Permalink
Replace colored printlns with tracing (FuelLabs#2764)
Browse files Browse the repository at this point in the history
* Replace colored printlns with tracing

* ERROR only

* Revert "ERROR only"

This reverts commit 0d0320d.

* Make tests read from both stdout and stderr

Co-authored-by: Joshua Batty <[email protected]>
  • Loading branch information
sdankel and JoshuaBatty authored Sep 15, 2022
1 parent 0b69f4d commit 542b435
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 55 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion forc-util/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ description = "Utility items shared between forc crates."

[dependencies]
annotate-snippets = { version = "0.9", features = ["color"] }
ansi_term = "0.12"
anyhow = "1"
dirs = "3.0.2"
sway-core = { version = "0.24.3", path = "../sway-core" }
sway-types = { version = "0.24.3", path = "../sway-types" }
sway-utils = { version = "0.24.3", path = "../sway-utils" }
termcolor = "1.1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["ansi", "env-filter", "json"] }
unicode-xid = "0.2.2"
87 changes: 40 additions & 47 deletions forc-util/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ use annotate_snippets::{
display_list::{DisplayList, FormatOptions},
snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
};
use ansi_term::Colour;
use anyhow::{bail, Result};
use std::env;
use std::ffi::OsStr;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::str;
use std::{env, io};
use sway_core::{error::LineCol, CompileError, CompileWarning, TreeType};
use sway_types::Spanned;
use sway_utils::constants;
use termcolor::{self, Color as TermColor, ColorChoice, ColorSpec, StandardStream, WriteColor};
use tracing_subscriber::filter::EnvFilter;
use tracing::{Level, Metadata};
use tracing_subscriber::{filter::EnvFilter, fmt::MakeWriter};

pub mod restricted;

Expand Down Expand Up @@ -201,65 +201,31 @@ pub fn print_on_failure(silent_mode: bool, warnings: &[CompileWarning], errors:
}

pub fn println_red(txt: &str) {
println_std_out(txt, TermColor::Red);
println_std_out(txt, Colour::Red);
}

pub fn println_green(txt: &str) {
println_std_out(txt, TermColor::Green);
}

pub fn print_blue_err(txt: &str) {
print_std_err(txt, TermColor::Blue);
println_std_out(txt, Colour::Green);
}

pub fn println_yellow_err(txt: &str) {
println_std_err(txt, TermColor::Yellow);
println_std_err(txt, Colour::Yellow);
}

pub fn println_red_err(txt: &str) {
println_std_err(txt, TermColor::Red);
println_std_err(txt, Colour::Red);
}

pub fn println_green_err(txt: &str) {
println_std_err(txt, TermColor::Green);
println_std_err(txt, Colour::Green);
}

pub fn print_std_out(txt: &str, color: TermColor) {
let stdout = StandardStream::stdout(ColorChoice::Always);
print_with_color(txt, color, stdout);
fn println_std_out(txt: &str, color: Colour) {
tracing::info!("{}", color.paint(txt));
}

fn println_std_out(txt: &str, color: TermColor) {
let stdout = StandardStream::stdout(ColorChoice::Always);
println_with_color(txt, color, stdout);
}

fn print_std_err(txt: &str, color: TermColor) {
let stdout = StandardStream::stderr(ColorChoice::Always);
print_with_color(txt, color, stdout);
}

fn println_std_err(txt: &str, color: TermColor) {
let stdout = StandardStream::stderr(ColorChoice::Always);
println_with_color(txt, color, stdout);
}

fn print_with_color(txt: &str, color: TermColor, stream: StandardStream) {
let mut stream = stream;
stream
.set_color(ColorSpec::new().set_fg(Some(color)))
.expect("internal printing error");
write!(&mut stream, "{}", txt).expect("internal printing error");
stream.reset().expect("internal printing error");
}

fn println_with_color(txt: &str, color: TermColor, stream: StandardStream) {
let mut stream = stream;
stream
.set_color(ColorSpec::new().set_fg(Some(color)))
.expect("internal printing error");
writeln!(&mut stream, "{}", txt).expect("internal printing error");
stream.reset().expect("internal printing error");
fn println_std_err(txt: &str, color: Colour) {
tracing::error!("{}", color.paint(txt));
}

fn format_err(err: &sway_core::CompileError) {
Expand Down Expand Up @@ -422,6 +388,32 @@ fn construct_window<'a>(

const LOG_FILTER: &str = "RUST_LOG";

// This allows us to write ERROR and WARN level logs to stderr and everything else to stdout.
// https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/trait.MakeWriter.html
struct StdioTracingWriter;
impl<'a> MakeWriter<'a> for StdioTracingWriter {
type Writer = Box<dyn io::Write>;

fn make_writer(&'a self) -> Self::Writer {
// We must have an implementation of `make_writer` that makes
// a "default" writer without any configuring metadata. Let's
// just return stdout in that case.
Box::new(io::stdout())
}

fn make_writer_for(&'a self, meta: &Metadata<'_>) -> Self::Writer {
// Here's where we can implement our special behavior. We'll
// check if the metadata's verbosity level is WARN or ERROR,
// and return stderr in that case.
if meta.level() <= &Level::WARN {
return Box::new(io::stderr());
}

// Otherwise, we'll return stdout.
Box::new(io::stdout())
}
}

/// A subscriber built from default `tracing_subscriber::fmt::SubscriberBuilder` such that it would match directly using `println!` throughout the repo.
///
/// `RUST_LOG` environment variable can be used to set different minimum level for the subscriber, default is `INFO`.
Expand All @@ -439,6 +431,7 @@ pub fn init_tracing_subscriber() {
.with_line_number(false)
.without_time()
.with_target(false)
.with_writer(StdioTracingWriter)
.init();
}

Expand Down
17 changes: 11 additions & 6 deletions test/src/e2e_vm_tests/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,12 @@ pub(crate) fn compile_to_bytes_verbose(
use std::io::Read;
tracing::info!(" Compiling {}", file_name);

let mut buf: Option<gag::BufferRedirect> = None;
let mut buf_stdout: Option<gag::BufferRedirect> = None;
let mut buf_stderr: Option<gag::BufferRedirect> = None;
if capture_output {
// Capture stdout to a buffer, compile the test and save stdout to a string.
buf = Some(gag::BufferRedirect::stdout().unwrap());
// Capture both stdout and stderr to buffers, compile the test and save to a string.
buf_stdout = Some(gag::BufferRedirect::stdout().unwrap());
buf_stderr = Some(gag::BufferRedirect::stderr().unwrap());
}

let manifest_dir = env!("CARGO_MANIFEST_DIR");
Expand All @@ -154,9 +156,12 @@ pub(crate) fn compile_to_bytes_verbose(

let mut output = String::new();
if capture_output {
let mut buf = buf.unwrap();
buf.read_to_string(&mut output).unwrap();
drop(buf);
let mut buf_stdout = buf_stdout.unwrap();
let mut buf_stderr = buf_stderr.unwrap();
buf_stdout.read_to_string(&mut output).unwrap();
buf_stderr.read_to_string(&mut output).unwrap();
drop(buf_stdout);
drop(buf_stderr);
}

(compiled, output)
Expand Down

0 comments on commit 542b435

Please sign in to comment.