Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Update: Logging with "tracing" #216

Merged
merged 2 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
389 changes: 207 additions & 182 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion cargo-near-build/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ eyre = "0.6.12"
camino = "1.1.1"
colored = "2.0"
dunce = "1"
log = "0.4"
tracing = "0.1.40"
bs58 = "0.5"
hex = "0.4.3"
sha2 = "0.10"
Expand Down
4 changes: 2 additions & 2 deletions cargo-near-build/src/cargo_native/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ where

if let Some(path) = working_dir {
let path = crate::fs::force_canonicalize_dir(path.as_ref())?;
log::debug!("Setting cargo working dir to '{}'", path);
tracing::debug!("Setting cargo working dir to '{}'", path);
cmd.current_dir(path);
}

Expand All @@ -134,7 +134,7 @@ where
ColorPreference::Never => cmd.args(["--color", "never"]),
};

log::info!("Invoking cargo: {:?}", cmd);
tracing::info!("Invoking cargo: {:?}", cmd);

let mut child = cmd
// capture the stdout to return from this function as bytes
Expand Down
8 changes: 4 additions & 4 deletions cargo-near-build/src/cargo_native/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,21 @@ pub fn wasm32_exists() -> bool {
match result {
Ok(wasm32_target_libdir_path) => {
if wasm32_target_libdir_path.exists() {
log::info!(
tracing::info!(
"Found {COMPILATION_TARGET} in {:?}",
wasm32_target_libdir_path
);
true
} else {
log::info!(
tracing::info!(
"Failed to find {COMPILATION_TARGET} in {:?}",
wasm32_target_libdir_path
);
false
}
}
Err(_) => {
log::error!("Some error in getting the target libdir, trying rustup..");
tracing::error!("Some error in getting the target libdir, trying rustup..");

invoke_rustup(["target", "list", "--installed"])
.map(|stdout| {
Expand Down Expand Up @@ -62,7 +62,7 @@ where
let mut cmd = Command::new(rustup);
cmd.args(args);

log::info!("Invoking rustup: {:?}", cmd);
tracing::info!("Invoking rustup: {:?}", cmd);

let child = cmd
.stdout(std::process::Stdio::piped())
Expand Down
4 changes: 2 additions & 2 deletions cargo-near-build/src/env_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub mod nep330 {
}

pub(crate) fn print_env() {
log::info!("Variables, relevant for reproducible builds:");
tracing::info!("Variables, relevant for reproducible builds:");
for key in [
BUILD_ENVIRONMENT,
BUILD_COMMAND,
Expand All @@ -41,7 +41,7 @@ pub mod nep330 {
let value = std::env::var(key)
.map(|val| format!("'{}'", val))
.unwrap_or("unset".to_string());
log::info!("{}={}", key, value);
tracing::info!("{}={}", key, value);
}
}
}
4 changes: 2 additions & 2 deletions cargo-near-build/src/near/abi/generate/dylib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn extract_abi_entries(
let dylib_path: &Utf8Path = &artifact.path;
let dylib_file_contents = fs::read(dylib_path)?;
let object = symbolic_debuginfo::Object::parse(&dylib_file_contents)?;
log::debug!(
tracing::debug!(
"A dylib was built at {:?} with format {} for architecture {}",
&dylib_path,
&object.file_format(),
Expand All @@ -26,7 +26,7 @@ pub fn extract_abi_entries(
if near_abi_symbols.is_empty() {
eyre::bail!("No NEAR ABI symbols found in the dylib");
}
log::debug!("Detected NEAR ABI symbols: {:?}", &near_abi_symbols);
tracing::debug!("Detected NEAR ABI symbols: {:?}", &near_abi_symbols);

let mut entries = vec![];
unsafe {
Expand Down
2 changes: 1 addition & 1 deletion cargo-near-build/src/near/build/export.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{env_keys, types::near::build::input::Opts};

pub fn nep_330_build_command(args: &Opts) -> eyre::Result<()> {
log::debug!(
tracing::debug!(
"compute `CARGO_NEAR_BUILD_COMMAND`, current executable: {:?}",
std::env::args().collect::<Vec<_>>()
);
Expand Down
4 changes: 2 additions & 2 deletions cargo-near-build/src/near/docker_build/subprocess_step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub fn run(
&container_paths.crate_path,
];
let stdin_is_terminal = std::io::stdin().is_terminal();
log::debug!("input device is a tty: {}", stdin_is_terminal);
tracing::debug!("input device is a tty: {}", stdin_is_terminal);
if stdin_is_terminal
&& std::env::var(env_keys::nep330::nonspec::SERVER_DISABLE_INTERACTIVE).is_err()
{
Expand All @@ -75,7 +75,7 @@ pub fn run(
docker_args.extend(vec![&docker_image, "/bin/bash", "-c"]);

docker_args.push(&cargo_cmd);
log::debug!("docker command : {:?}", docker_args);
tracing::debug!("docker command : {:?}", docker_args);
docker_args
};

Expand Down
8 changes: 4 additions & 4 deletions cargo-near-build/src/types/cargo/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl CrateMetadata {
manifest_path,
raw_metadata: metadata,
};
log::trace!("crate metadata : {:#?}", crate_metadata);
tracing::trace!("crate metadata : {:#?}", crate_metadata);
Ok(crate_metadata)
}

Expand All @@ -57,7 +57,7 @@ impl CrateMetadata {
} else {
self.target_directory.clone()
};
log::debug!("resolved output directory: {}", result);
tracing::debug!("resolved output directory: {}", result);
Ok(result)
}

Expand All @@ -71,13 +71,13 @@ fn get_cargo_metadata(
manifest_path: &ManifestPath,
no_locked: bool,
) -> eyre::Result<(cargo_metadata::Metadata, Package)> {
log::info!("Fetching cargo metadata for {}", manifest_path.path);
tracing::info!("Fetching cargo metadata for {}", manifest_path.path);
let mut cmd = MetadataCommand::new();
if !no_locked {
cmd.other_options(["--locked".to_string()]);
}
let cmd = cmd.manifest_path(&manifest_path.path);
log::debug!("metadata command: {:#?}", cmd.cargo_command());
tracing::debug!("metadata command: {:#?}", cmd.cargo_command());
let metadata = cmd.exec();
if let Err(cargo_metadata::Error::CargoMetadata { stderr }) = metadata.as_ref() {
if stderr.contains("remove the --locked flag") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ impl ClonedRepo {
}
})?
};
log::info!(
tracing::info!(
"obtained tmp_crate_metadata.target_directory: {}",
tmp_crate_metadata.target_directory
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Crate {
crate_root: initial_crate_root.clone(),
head,
};
log::debug!("crate in repo: {:?}", result);
tracing::debug!("crate in repo: {:?}", result);
Ok(result)
}
}
Expand Down
8 changes: 6 additions & 2 deletions cargo-near/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ cargo-near-build = { version = "0.1.0", path = "../cargo-near-build", features =
] }
clap = { version = "4.0.18", features = ["derive", "env"] }
colored = "2.0"
env_logger = "0.11.5"
log = "0.4"
serde = "1.0.197"
color-eyre = "0.6"
inquire = "0.7"
Expand All @@ -44,7 +42,13 @@ interactive-clap = "0.3"
interactive-clap-derive = "0.3"
near-cli-rs = { version = "0.15.0", default-features = false }
reqwest = "0.12.5"
indicatif = "0.17.8"
indenter = "0.3"
tracing-core = "0.1.32"
tracing = "0.1.40"
tracing-log = "0.2.0"
tracing-indicatif = "0.3.6"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tokio = { version = "1.0", default-features = false, features = [
"rt-multi-thread",
] }
Expand Down
44 changes: 18 additions & 26 deletions cargo-near/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,38 @@
use std::env;
use std::io::{IsTerminal, Write};
use std::io::IsTerminal;

use cargo_near_build::env_keys;
use colored::Colorize;
use interactive_clap::ToCliArgs;
use log::Level;

use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::{fmt::format, prelude::*};

pub use near_cli_rs::CliResult;

use cargo_near::Cmd;

fn main() -> CliResult {
let mut builder = env_logger::Builder::from_env(env_logger::Env::default());

let environment = if std::env::var(env_keys::nep330::BUILD_ENVIRONMENT).is_ok() {
"container".cyan()
} else {
"host".purple()
};
let my_formatter = cargo_near::types::my_formatter::MyFormatter::from_environment(environment);

let format = format::debug_fn(move |writer, _field, value| write!(writer, "{:?}", value));

let env_filter = EnvFilter::from_default_env();

builder
.format(move |buf, record| {
let level = format!("[{}]", record.level());
let level = match record.level() {
Level::Error => level.red(),
Level::Warn => level.yellow(),
Level::Info => level.cyan(),
Level::Debug => level.truecolor(100, 100, 100),
Level::Trace => level.truecolor(200, 200, 200),
};
let ts = buf.timestamp_seconds();
writeln!(
buf,
" {}-[{}] {}:{} {} - {}",
level,
environment,
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
ts,
record.args()
)
})
tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.event_format(my_formatter)
.fmt_fields(format)
.with_filter(env_filter),
)
.init();

match env::var("NO_COLOR") {
Expand Down
1 change: 1 addition & 0 deletions cargo-near/src/types/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod color_preference_cli;
pub mod my_formatter;
pub mod utf8_path_buf;
58 changes: 58 additions & 0 deletions cargo-near/src/types/my_formatter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use colored::Colorize;
use tracing::Level;
use tracing_core::{Event, Subscriber};
use tracing_log::NormalizeEvent;
use tracing_subscriber::fmt::{
format::{self, FormatEvent, FormatFields},
FmtContext,
};
use tracing_subscriber::registry::LookupSpan;

#[derive(Debug)]
pub struct MyFormatter {
environment: colored::ColoredString,
}

impl MyFormatter {
pub fn from_environment(environment: colored::ColoredString) -> Self {
Self { environment }
}
}

impl<S, N> FormatEvent<S, N> for MyFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
mut writer: format::Writer<'_>,
event: &Event<'_>,
) -> std::fmt::Result {
let normalized_meta = event.normalized_metadata();
let metadata = normalized_meta.as_ref().unwrap_or_else(|| event.metadata());

let level = format!("[{}]", metadata.level());
let fmt_level = match *metadata.level() {
Level::ERROR => level.red(),
Level::WARN => level.yellow(),
Level::INFO => level.cyan(),
Level::DEBUG => level.truecolor(100, 100, 100),
Level::TRACE => level.truecolor(200, 200, 200),
};

write!(
&mut writer,
"{}-[{}] {}:{} - ",
fmt_level,
self.environment,
metadata.file().unwrap_or("log"),
metadata.line().unwrap_or_default()
)?;

ctx.field_format().format_fields(writer.by_ref(), event)?;

writeln!(writer)
}
}
Loading