Skip to content

Align logging to match cargo's style #410

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

Merged
merged 3 commits into from
May 3, 2025
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
10 changes: 10 additions & 0 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 @@ -72,6 +72,7 @@ toml_edit = { version = "0.22.22", default-features = false, features = [
# Logging crates
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
ansi_term = "0.12.1"

# Web dependencies

Expand Down
50 changes: 44 additions & 6 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use ansi_term::Color::{Blue, Green, Purple, Red, Yellow};
use anyhow::Result;
use bevy_cli::{build::args::BuildArgs, run::RunArgs};
use clap::{Args, CommandFactory, Parser, Subcommand};
use tracing_subscriber::prelude::*;
use tracing_subscriber::{
fmt::{self, FormatEvent, FormatFields, format::Writer},
prelude::*,
};

fn main() -> Result<()> {
let cli = Cli::parse();
Expand All @@ -18,13 +22,10 @@ fn main() -> Result<()> {
|filter| tracing_subscriber::EnvFilter::new(format!("bevy_cli={filter}")),
);

let fmt_layer = tracing_subscriber::fmt::layer()
// remove timestamps
.without_time()
let fmt_layer = fmt::layer()
.event_format(CargoStyleFormatter)
// enable colorized output if stderr is a terminal
.with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
// remove the module path from the log messages
.with_target(false)
.with_filter(env);

tracing_subscriber::registry().with(fmt_layer).init();
Expand Down Expand Up @@ -116,3 +117,40 @@ pub struct NewArgs {
#[arg(short, long, default_value = "main")]
pub branch: String,
}

/// Align the log formatting to match `cargo`'s style.
pub struct CargoStyleFormatter;

impl<S, N> FormatEvent<S, N> for CargoStyleFormatter
where
S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &fmt::FmtContext<'_, S, N>,
mut writer: Writer<'_>,
event: &tracing::Event<'_>,
) -> std::fmt::Result {
let meta = event.metadata();

let (color, level) = match *meta.level() {
tracing::Level::ERROR => (Red, "error"),
tracing::Level::WARN => (Yellow, "warning"),
tracing::Level::INFO => (Green, "info"),
tracing::Level::DEBUG => (Blue, "debug"),
tracing::Level::TRACE => (Purple, "trace"),
};

// Apply color if desired
let level = if writer.has_ansi_escapes() {
color.bold().paint(level).to_string()
} else {
level.to_string()
};

write!(writer, "{level}: ",)?;
ctx.format_fields(writer.by_ref(), event)?;
writeln!(writer)
}
}
2 changes: 1 addition & 1 deletion src/build/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl BuildArgs {
return;
}

tracing::debug!("Using defaults from bevy_cli config:\n{config}");
tracing::debug!("using defaults from bevy_cli config:\n{config}");
if self.cargo_args.compilation_args.target.is_none() {
self.cargo_args.compilation_args.target = config.target().map(ToOwned::to_owned);
}
Expand Down
10 changes: 5 additions & 5 deletions src/external_cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl CommandExt {

if self.package.is_some() || self.target.is_some() {
tracing::warn!(
"Failed to run {}, trying to find automatic fix...",
"failed to run {}, trying to find automatic fix...",
self.inner.get_program().to_string_lossy()
)
}
Expand Down Expand Up @@ -211,10 +211,10 @@ impl CommandExt {
.collect::<Vec<_>>()
.join(",");

self.log(format!("Running: `{self}`").as_str());
self.log(format!("running: `{self}`").as_str());

if !envs.is_empty() {
self.log(&format!("With env: {envs}"));
self.log(&format!("with env: {envs}"));
}
}

Expand All @@ -236,7 +236,7 @@ impl CommandExt {

anyhow::ensure!(
status.success(),
"Command `{self}` exited with status code {}",
"command `{self}` exited with status code {}",
status
);

Expand All @@ -261,7 +261,7 @@ impl CommandExt {

anyhow::ensure!(
output.status.success(),
"Command `{self}` exited with status code {}",
"command `{self}` exited with status code {}",
output.status
);

Expand Down
4 changes: 2 additions & 2 deletions src/external_cli/rustup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ pub(crate) fn install_target_if_needed<T: AsRef<OsStr>>(
if !auto_install.confirm(format!(
"Compilation target `{target_str}` is missing, should I install it for you?",
))? {
anyhow::bail!("User does not want to install target `{target_str}`.");
anyhow::bail!("user does not want to install target `{target_str}`.");
}

info!("Installing missing target: `{target_str}`");
info!("installing missing target: `{target_str}`");

CommandExt::new(program())
.arg("target")
Expand Down
4 changes: 2 additions & 2 deletions src/external_cli/wasm_opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub(crate) fn optimize_path(
.artifact_directory
.clone()
.join(format!("{}_bg.wasm", bin_target.bin_name));
info!("Optimizing with wasm-opt...");
info!("optimizing with wasm-opt...");

let start = Instant::now();
let size_before = fs::metadata(&path)?.len();
Expand All @@ -39,7 +39,7 @@ pub(crate) fn optimize_path(
let duration = start.elapsed();

info!(
"Finished in {duration:.2?}. Size reduced by {:.0}%.",
"finished in {duration:.2?}. Size reduced by {:.0}%.",
size_reduction * 100.
);

Expand Down
2 changes: 1 addition & 1 deletion src/run/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl RunArgs {
return;
}

tracing::debug!("Using defaults from bevy_cli config:\n{config}");
tracing::debug!("using defaults from bevy_cli config:\n{config}");
if self.cargo_args.compilation_args.target.is_none() {
self.cargo_args.compilation_args.target = config.target().map(ToOwned::to_owned);
}
Expand Down
8 changes: 4 additions & 4 deletions src/web/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub fn build_web(

let cargo_args = args.cargo_args_builder();

info!("Compiling to WebAssembly...");
info!("compiling to WebAssembly...");

cargo::build::command()
// Wasm targets are not installed by default
Expand All @@ -54,7 +54,7 @@ pub fn build_web(
.env("RUSTFLAGS", args.cargo_args.common_args.rustflags.clone())
.ensure_status(args.auto_install())?;

info!("Bundling JavaScript bindings...");
info!("bundling JavaScript bindings...");
wasm_bindgen::bundle(metadata, bin_target, args.auto_install())?;

#[cfg(feature = "wasm-opt")]
Expand All @@ -68,10 +68,10 @@ pub fn build_web(
bin_target,
web_args.create_packed_bundle,
)
.context("Failed to create web bundle")?;
.context("failed to create web bundle")?;

if let WebBundle::Packed(PackedBundle { path }) = &web_bundle {
info!("Created bundle at file://{}", path.display());
info!("created bundle at file://{}", path.display());
}

Ok(web_bundle)
Expand Down
10 changes: 5 additions & 5 deletions src/web/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub fn create_web_bundle(
let index = if index_path.exists() {
Index::File(index_path)
} else {
info!("No custom `web` folder found, using defaults.");
info!("no custom `web` folder found, using defaults.");
Index::Content(default_index(bin_target))
};

Expand Down Expand Up @@ -119,7 +119,7 @@ pub fn create_web_bundle(

// Build artifacts
tracing::debug!(
"Copying build artifacts from file://{}",
"copying build artifacts from file://{}",
linked.build_artifact_path.to_string_lossy()
);
fs::create_dir_all(base_path.join("build"))?;
Expand All @@ -137,7 +137,7 @@ pub fn create_web_bundle(
// Assets
if let Some(assets_path) = linked.assets_path {
tracing::debug!(
"Copying assets from file://{}",
"copying assets from file://{}",
assets_path.to_string_lossy()
);
fs_extra::dir::copy(
Expand All @@ -154,7 +154,7 @@ pub fn create_web_bundle(
// Custom web assets
if custom_web_folder.exists() {
tracing::debug!(
"Copying custom web assets from file://{}",
"copying custom web assets from file://{}",
custom_web_folder.to_string_lossy()
);
fs_extra::dir::copy(
Expand All @@ -170,7 +170,7 @@ pub fn create_web_bundle(
}

// Index (pre-processed)
tracing::debug!("Writing index.html");
tracing::debug!("writing index.html");
fs::write(base_path.join("index.html"), &index)
.context("failed to write processed index.html")?;

Expand Down
6 changes: 3 additions & 3 deletions src/web/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@ pub(crate) fn run_web(
// Serving the app is blocking, so we open the page first
if web_args.open {
match webbrowser::open(&url) {
Ok(()) => info!("Your app is running at <{url}>!"),
Ok(()) => info!("your app is running at <{url}>!"),
Err(error) => {
error!(
"Failed to open the browser automatically, open the app at <{url}>. (Error: {error:?})"
"failed to open the browser automatically, open the app at <{url}>. (Error: {error:?})"
);
}
}
} else {
info!("Open your app at <{url}>!");
info!("open your app at <{url}>!");
}

serve(web_bundle, port, header_map)?;
Expand Down
2 changes: 1 addition & 1 deletion src/web/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub(crate) async fn serve(
let mut router = Router::new();

if !header_map.is_empty() {
tracing::debug!("Adding response headers {header_map:?}");
tracing::debug!("adding response headers {header_map:?}");
}

match web_bundle.clone() {
Expand Down