Skip to content

Commit

Permalink
refactor(forc): extract tracing utils from forc-util into dedicated…
Browse files Browse the repository at this point in the history
… `forc-tracing` (FuelLabs#3108)

closes FuelLabs#3107 

For the motivation for this PR, refer to the issue linked above.

This PR extracts all `tracing` related util functions from `forc-util`
and puts them into a dedicated `forc-tracing` crate. There is a minor
code change
[here](https://github.com/FuelLabs/sway/pull/3108/files#diff-fb650e8292a5d6bc84d8a261393ff2cabe324b5162c40ee5cf23af57ff4dcf58R161-R164)
because it is the only place that `forc-explore` uses `forc-util` (so we
can eliminate the dependency entirely), but other than that this PR is
mostly just moving code around and updating deps as required for crates
dependent on the moved `tracing` utils.

Co-authored-by: Joshua Batty <[email protected]>
  • Loading branch information
spiral-ladder and JoshuaBatty authored Oct 24, 2022
1 parent 58db549 commit 642c4b0
Show file tree
Hide file tree
Showing 31 changed files with 209 additions and 161 deletions.
22 changes: 19 additions & 3 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ members = [
"forc-plugins/forc-explore",
"forc-plugins/forc-fmt",
"forc-plugins/forc-lsp",
"forc-tracing",
"forc-util",
"scripts/examples-checker",
"scripts/mdbook-forc-documenter",
Expand Down
1 change: 1 addition & 0 deletions forc-pkg/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ description = "Building, locking, fetching and updating Sway projects as Forc pa

[dependencies]
anyhow = "1"
forc-tracing = { version = "0.27.0", path = "../forc-tracing" }
forc-util = { version = "0.27.0", path = "../forc-util" }
fuel-crypto = "0.6"
fuel-tx = { version = "0.18", features = ["serde"] }
Expand Down
2 changes: 1 addition & 1 deletion forc-pkg/src/lock.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{pkg, DepKind, Edge};
use anyhow::{anyhow, Result};
use forc_util::{println_green, println_red};
use forc_tracing::{println_green, println_red};
use petgraph::{visit::EdgeRef, Direction};
use serde::{Deserialize, Serialize};
use std::{
Expand Down
3 changes: 2 additions & 1 deletion forc-pkg/src/manifest.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::pkg::{manifest_file_missing, parsing_failed, wrong_program_type};
use anyhow::{anyhow, bail, Result};
use forc_util::{find_manifest_dir, println_yellow_err, validate_name};
use forc_tracing::println_yellow_err;
use forc_util::{find_manifest_dir, validate_name};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
Expand Down
1 change: 1 addition & 0 deletions forc-plugins/forc-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ anyhow = "1"
async-trait = "0.1.58"
clap = { version = "3", features = ["derive", "env"] }
forc-pkg = { version = "0.27.0", path = "../../forc-pkg" }
forc-tracing = { version = "0.27.0", path = "../../forc-tracing" }
forc-util = { version = "0.27.0", path = "../../forc-util" }
fuel-crypto = "0.6"
fuel-gql-client = { version = "0.10", default-features = false }
Expand Down
2 changes: 1 addition & 1 deletion forc-plugins/forc-client/src/bin/deploy/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use forc_client::ops::deploy::{cmd::DeployCommand, op::deploy};
use forc_util::init_tracing_subscriber;
use forc_tracing::init_tracing_subscriber;
use std::process;

use clap::Parser;
Expand Down
2 changes: 1 addition & 1 deletion forc-plugins/forc-client/src/bin/run/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use forc_client::ops::run::{cmd::RunCommand, op::run};
use forc_util::init_tracing_subscriber;
use forc_tracing::init_tracing_subscriber;
use std::process;

use clap::Parser;
Expand Down
3 changes: 2 additions & 1 deletion forc-plugins/forc-explore/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ description = "A `forc` plugin for running the fuel block explorer."
[dependencies]
anyhow = "1"
clap = { version = "3", features = ["derive"] }
forc-util = { version = "0.27.0", path = "../../forc-util" }
dirs = "3.0.2"
forc-tracing = { version = "0.27.0", path = "../../forc-tracing" }
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1.0", features = ["derive"] }
tar = "0.4"
Expand Down
8 changes: 5 additions & 3 deletions forc-plugins/forc-explore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
use anyhow::{anyhow, Context, Result};
use clap::Parser;
use forc_util::init_tracing_subscriber;
use forc_util::println_green;
use forc_tracing::{init_tracing_subscriber, println_green};
use serde::Deserialize;
use std::{
fs::{self, File},
Expand Down Expand Up @@ -159,7 +158,10 @@ pub(crate) mod path {
use std::path::PathBuf;

pub fn explorer_directory() -> PathBuf {
forc_util::user_forc_directory().join("explorer")
dirs::home_dir()
.expect("unable to find the user home directory")
.join(".forc")
.join("explorer")
}

pub fn web_app() -> PathBuf {
Expand Down
1 change: 1 addition & 0 deletions forc-plugins/forc-fmt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ description = "A `forc` plugin for running the Sway code formatter."
[dependencies]
anyhow = "1"
clap = { version = "3", features = ["derive"] }
forc-tracing = { version = "0.27.0", path = "../../forc-tracing" }
forc-util = { version = "0.27.0", path = "../../forc-util" }
prettydiff = "0.5"
sway-core = { version = "0.27.0", path = "../../sway-core" }
Expand Down
3 changes: 2 additions & 1 deletion forc-plugins/forc-fmt/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use std::{
use taplo::formatter as taplo_fmt;
use tracing::{error, info};

use forc_util::{find_manifest_dir, init_tracing_subscriber, println_green, println_red};
use forc_tracing::{init_tracing_subscriber, println_green, println_red};
use forc_util::find_manifest_dir;
use sway_core::BuildConfig;
use sway_utils::{constants, get_sway_files};
use swayfmt::Formatter;
Expand Down
14 changes: 14 additions & 0 deletions forc-tracing/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "forc-tracing"
version = "0.27.0"
authors = ["Fuel Labs <[email protected]>"]
edition = "2021"
homepage = "https://fuel.network/"
license = "Apache-2.0"
repository = "https://github.com/FuelLabs/sway"
description = "Tracing utility shared between forc crates."

[dependencies]
ansi_term = "0.12"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["ansi", "env-filter", "json"] }
140 changes: 140 additions & 0 deletions forc-tracing/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
//! Utility items shared between forc crates.
use ansi_term::Colour;
use std::str;
use std::{env, io};
use tracing::{Level, Metadata};
use tracing_subscriber::{
filter::{EnvFilter, LevelFilter},
fmt::MakeWriter,
};

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

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

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

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

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

fn println_std_out(txt: &str, color: Colour) {
tracing::info!("{}", color.paint(txt));
}

fn println_std_err(txt: &str, color: Colour) {
tracing::error!("{}", color.paint(txt));
}

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 {
writer_mode: TracingWriterMode,
}

impl<'a> MakeWriter<'a> for StdioTracingWriter {
type Writer = Box<dyn io::Write>;

fn make_writer(&'a self) -> Self::Writer {
if self.writer_mode == TracingWriterMode::Stderr {
Box::new(io::stderr())
} else {
// 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 self.writer_mode == TracingWriterMode::Stderr
|| (self.writer_mode == TracingWriterMode::Stdio && meta.level() <= &Level::WARN)
{
return Box::new(io::stderr());
}

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

#[derive(PartialEq, Eq)]
pub enum TracingWriterMode {
/// Write ERROR and WARN to stderr and everything else to stdout.
Stdio,
/// Write everything to stdout.
Stdout,
/// Write everything to stderr.
Stderr,
}

#[derive(Default)]
pub struct TracingSubscriberOptions {
pub verbosity: Option<u8>,
pub silent: Option<bool>,
pub log_level: Option<LevelFilter>,
pub writer_mode: Option<TracingWriterMode>,
}

/// 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`.
pub fn init_tracing_subscriber(options: TracingSubscriberOptions) {
let env_filter = match env::var_os(LOG_FILTER) {
Some(_) => EnvFilter::try_from_default_env().expect("Invalid `RUST_LOG` provided"),
None => EnvFilter::new("info"),
};

let level_filter = options
.log_level
.or_else(|| {
options.verbosity.and_then(|verbosity| {
match verbosity {
1 => Some(LevelFilter::DEBUG), // matches --verbose or -v
2 => Some(LevelFilter::TRACE), // matches -vv
_ => None,
}
})
})
.or_else(|| {
options.silent.and_then(|silent| match silent {
true => Some(LevelFilter::OFF),
_ => None,
})
});

let builder = tracing_subscriber::fmt::Subscriber::builder()
.with_env_filter(env_filter)
.with_ansi(true)
.with_level(false)
.with_file(false)
.with_line_number(false)
.without_time()
.with_target(false)
.with_writer(StdioTracingWriter {
writer_mode: options.writer_mode.unwrap_or(TracingWriterMode::Stdio),
});

// If log level, verbosity, or silent mode is set, it overrides the RUST_LOG setting
if let Some(level_filter) = level_filter {
builder.with_max_level(level_filter).init();
} else {
builder.init();
}
}
1 change: 1 addition & 0 deletions forc-util/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ annotate-snippets = { version = "0.9", features = ["color"] }
ansi_term = "0.12"
anyhow = "1"
dirs = "3.0.2"
forc-tracing = { version = "0.27.0", path = "../forc-tracing" }
sway-core = { version = "0.27.0", path = "../sway-core" }
sway-error = { version = "0.27.0", path = "../sway-error" }
sway-types = { version = "0.27.0", path = "../sway-types" }
Expand Down
Loading

0 comments on commit 642c4b0

Please sign in to comment.