Switch to tracing for the cli (#2137)

* switch to tracing in the dioxus-cli

* bump manganis

* fix manganis features

* only print processing assets if skip assets is disabled

* switch all logs to tracing

* switch to published version of manganis

* undo all changes to cargo.toml

* remove reference to log
This commit is contained in:
Evan Almloff 2024-03-25 15:21:51 -05:00 committed by GitHub
parent da3b066934
commit 2ac4bdb673
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 365 additions and 416 deletions

592
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -15,9 +15,6 @@ thiserror = { workspace = true }
wasm-bindgen-cli-support = "0.2"
colored = "2.0.0"
dioxus-cli-config = { workspace = true, features = ["cli"] }
# features
log = "0.4.14"
fern = { version = "0.6.0", features = ["colored"] }
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
@ -81,7 +78,7 @@ tauri-bundler = { version = "=1.4.*", features = ["native-tls-vendored"] }
syn = { workspace = true }
prettyplease = { workspace = true }
manganis-cli-support = { workspace = true, features = ["webp", "html"] }
manganis-cli-support = { workspace = true, features = ["html"] }
dioxus-autofmt = { workspace = true }
dioxus-check = { workspace = true }
@ -94,6 +91,8 @@ interprocess = { workspace = true }
# interprocess-docfix = { version = "1.2.2" }
ignore = "0.4.22"
env_logger = "0.11.3"
tracing-subscriber = "0.3.18"
tracing.workspace = true
[features]
default = []

View file

@ -97,7 +97,7 @@ pub fn build_web(
let _guard = dioxus_cli_config::__private::save_config(config);
// [1] Build the .wasm module
log::info!("🚅 Running build command...");
tracing::info!("🚅 Running build command...");
// If the user has rustup, we can check if the wasm32-unknown-unknown target is installed
// Otherwise we can just assume it is installed - which i snot great...
@ -105,7 +105,7 @@ pub fn build_web(
if let Ok(wasm_check_command) = Command::new("rustup").args(["show"]).output() {
let wasm_check_output = String::from_utf8(wasm_check_command.stdout).unwrap();
if !wasm_check_output.contains("wasm32-unknown-unknown") {
log::info!("wasm32-unknown-unknown target not detected, installing..");
tracing::info!("wasm32-unknown-unknown target not detected, installing..");
let _ = Command::new("rustup")
.args(["target", "add", "wasm32-unknown-unknown"])
.output()?;
@ -167,7 +167,7 @@ pub fn build_web(
.context("No output location found")?
.with_extension("wasm");
log::info!("Running wasm-bindgen");
tracing::info!("Running wasm-bindgen");
let bindgen_result = panic::catch_unwind(move || {
// [3] Bindgen the final binary for use easy linking
let mut bindgen_builder = Bindgen::new();
@ -191,7 +191,7 @@ pub fn build_web(
}
// check binaryen:wasm-opt tool
log::info!("Running optimization with wasm-opt...");
tracing::info!("Running optimization with wasm-opt...");
let dioxus_tools = dioxus_config.application.tools.clone();
if dioxus_tools.contains_key("binaryen") {
let info = dioxus_tools.get("binaryen").unwrap();
@ -202,7 +202,7 @@ pub fn build_web(
if sub.contains_key("wasm_opt")
&& sub.get("wasm_opt").unwrap().as_bool().unwrap_or(false)
{
log::info!("Optimizing WASM size with wasm-opt...");
tracing::info!("Optimizing WASM size with wasm-opt...");
let target_file = out_dir
.join("assets")
.join("dioxus")
@ -221,12 +221,12 @@ pub fn build_web(
}
}
} else {
log::warn!(
tracing::warn!(
"Binaryen tool not found, you can use `dx tool add binaryen` to install it."
);
}
} else {
log::info!("Skipping optimization with wasm-opt, binaryen tool not found.");
tracing::info!("Skipping optimization with wasm-opt, binaryen tool not found.");
}
// [5][OPTIONAL] If tailwind is enabled and installed we run it to generate the CSS
@ -236,7 +236,7 @@ pub fn build_web(
if tailwind.is_installed() {
if let Some(sub) = info.as_table() {
log::info!("Building Tailwind bundle CSS file...");
tracing::info!("Building Tailwind bundle CSS file...");
let input_path = match sub.get("input") {
Some(val) => val.as_str().unwrap(),
@ -262,7 +262,7 @@ pub fn build_web(
tailwind.call("tailwindcss", args)?;
}
} else {
log::warn!(
tracing::warn!(
"Tailwind tool not found, you can use `dx tool add tailwindcss` to install it."
);
}
@ -278,7 +278,7 @@ pub fn build_web(
depth: 0,
};
log::info!("Copying public assets to the output directory...");
tracing::info!("Copying public assets to the output directory...");
if asset_dir.is_dir() {
for entry in std::fs::read_dir(config.asset_dir())?.flatten() {
let path = entry.path();
@ -288,7 +288,7 @@ pub fn build_web(
match fs_extra::dir::copy(&path, &out_dir, &copy_options) {
Ok(_) => {}
Err(_e) => {
log::warn!("Error copying dir: {}", _e);
tracing::warn!("Error copying dir: {}", _e);
}
}
for ignore in &ignore_files {
@ -302,8 +302,8 @@ pub fn build_web(
}
}
log::info!("Processing assets");
let assets = if !skip_assets {
tracing::info!("Processing assets");
let assets = asset_manifest(executable.executable(), config);
process_assets(config, &assets)?;
Some(assets)
@ -327,7 +327,7 @@ pub fn build_desktop(
skip_assets: bool,
rust_flags: Option<String>,
) -> Result<BuildResult> {
log::info!("🚅 Running build [Desktop] command...");
tracing::info!("🚅 Running build [Desktop] command...");
let t_start = std::time::Instant::now();
let ignore_files = build_assets(config)?;
@ -410,7 +410,7 @@ pub fn build_desktop(
match fs_extra::dir::copy(&path, &config.out_dir(), &copy_options) {
Ok(_) => {}
Err(e) => {
log::warn!("Error copying dir: {}", e);
tracing::warn!("Error copying dir: {}", e);
}
}
for ignore in &ignore_files {
@ -425,6 +425,7 @@ pub fn build_desktop(
}
let assets = if !skip_assets {
tracing::info!("Processing assets");
let assets = asset_manifest(config.executable.executable(), config);
// Collect assets
process_assets(config, &assets)?;
@ -435,7 +436,7 @@ pub fn build_desktop(
None
};
log::info!(
tracing::info!(
"🚩 Build completed: [./{}]",
config.dioxus_config.application.out_dir.clone().display()
);
@ -502,9 +503,9 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<CargoBuildResult> {
}
Message::BuildFinished(finished) => {
if finished.success {
log::info!("👑 Build done.");
tracing::info!("👑 Build done.");
} else {
log::info!("❌ Build failed.");
tracing::info!("❌ Build failed.");
return Err(anyhow::anyhow!("Build failed"));
}
}
@ -736,7 +737,7 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
if res.is_ok() {
result.push(path);
} else {
log::error!("{:?}", res);
tracing::error!("{:?}", res);
}
}
}

View file

@ -37,7 +37,7 @@ impl Config {
} => {
let conf_path = crate_root.join("Dioxus.toml");
if conf_path.is_file() && !force {
log::warn!(
tracing::warn!(
"config file `Dioxus.toml` already exist, use `--force` to overwrite it."
);
return Ok(());
@ -47,7 +47,7 @@ impl Config {
.replace("{{project-name}}", &name)
.replace("{{default-platform}}", &platform);
file.write_all(content.as_bytes())?;
log::info!("🚩 Init config file completed.");
tracing::info!("🚩 Init config file completed.");
}
Config::FormatPrint {} => {
println!(
@ -60,7 +60,7 @@ impl Config {
let mut file = File::create(html_path)?;
let content = include_str!("../assets/index.html");
file.write_all(content.as_bytes())?;
log::info!("🚩 Create custom html file done.");
tracing::info!("🚩 Create custom html file done.");
}
}
Ok(())

View file

@ -32,9 +32,9 @@ pub fn post_create(path: &PathBuf) -> Result<()> {
let cmd = cmd.arg("fmt").current_dir(path);
let output = cmd.output().expect("failed to execute process");
if !output.status.success() {
log::error!("cargo fmt failed");
log::error!("stdout: {}", String::from_utf8_lossy(&output.stdout));
log::error!("stderr: {}", String::from_utf8_lossy(&output.stderr));
tracing::error!("cargo fmt failed");
tracing::error!("stdout: {}", String::from_utf8_lossy(&output.stdout));
tracing::error!("stderr: {}", String::from_utf8_lossy(&output.stderr));
}
// then format the toml
@ -64,7 +64,7 @@ pub fn post_create(path: &PathBuf) -> Result<()> {
let mut file = std::fs::File::create(readme_path)?;
file.write_all(new_readme.as_bytes())?;
log::info!("Generated project at {}", path.display());
tracing::info!("Generated project at {}", path.display());
Ok(())
}

View file

@ -27,11 +27,11 @@ impl Plugin {
if let Some(v) = plugin_dir.to_str() {
println!("{}", v);
} else {
log::error!("Plugin path get failed.");
tracing::error!("Plugin path get failed.");
}
}
Plugin::Add { name: _ } => {
log::info!("You can use `dx plugin app-path` to get Installation position");
tracing::info!("You can use `dx plugin app-path` to get Installation position");
}
}
Ok(())

View file

@ -105,7 +105,7 @@ fn indent_and_write(raw: &str, idx: usize, out: &mut String) {
fn determine_input(file: Option<String>, raw: Option<String>) -> Result<String> {
// Make sure not both are specified
if file.is_some() && raw.is_some() {
log::error!("Only one of --file or --raw should be specified.");
tracing::error!("Only one of --file or --raw should be specified.");
exit(0);
}

View file

@ -15,8 +15,5 @@ pub use cli::*;
pub mod error;
pub use error::*;
pub mod logging;
pub use logging::*;
#[cfg(feature = "plugin")]
pub mod plugin;

View file

@ -1,46 +0,0 @@
use fern::colors::{Color, ColoredLevelConfig};
pub fn set_up_logging() {
// configure colors for the whole line
let colors_line = ColoredLevelConfig::new()
.error(Color::Red)
.warn(Color::Yellow)
// we actually don't need to specify the color for debug and info, they are white by default
.info(Color::White)
.debug(Color::White)
// depending on the terminals color scheme, this is the same as the background color
.trace(Color::BrightBlack);
// configure colors for the name of the level.
// since almost all of them are the same as the color for the whole line, we
// just clone `colors_line` and overwrite our changes
let colors_level = colors_line.info(Color::Green);
// here we set up our fern Dispatch
fern::Dispatch::new()
.format(move |out, message, record| {
out.finish(format_args!(
"{color_line}[{level}{color_line}] {message}\x1B[0m",
color_line = format_args!(
"\x1B[{}m",
colors_line.get_color(&record.level()).to_fg_str()
),
level = colors_level.color(record.level()),
));
})
.level(match std::env::var("DIOXUS_LOG") {
Ok(level) => match level.to_lowercase().as_str() {
"error" => log::LevelFilter::Error,
"warn" => log::LevelFilter::Warn,
"info" => log::LevelFilter::Info,
"debug" => log::LevelFilter::Debug,
"trace" => log::LevelFilter::Trace,
_ => {
panic!("Invalid log level: {}", level)
}
},
Err(_) => log::LevelFilter::Info,
})
.chain(std::io::stdout())
.apply()
.unwrap();
}

View file

@ -11,10 +11,7 @@ use Commands::*;
async fn main() -> anyhow::Result<()> {
let args = Cli::parse();
#[cfg(debug_assertions)]
env_logger::init();
// set_up_logging();
tracing_subscriber::fmt::init();
match args.action {
Translate(opts) => opts
@ -53,7 +50,7 @@ async fn main() -> anyhow::Result<()> {
let _dioxus_config = DioxusConfig::load(Some(bin.clone()))
.context("Failed to load Dioxus config because")?
.unwrap_or_else(|| {
log::info!("You appear to be creating a Dioxus project from scratch; we will use the default config");
tracing::info!("You appear to be creating a Dioxus project from scratch; we will use the default config");
DioxusConfig::default()
});

View file

@ -1,27 +1,26 @@
use log;
use mlua::UserData;
pub struct PluginLogger;
impl UserData for PluginLogger {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_function("trace", |_, info: String| {
log::trace!("{}", info);
tracing::trace!("{}", info);
Ok(())
});
methods.add_function("info", |_, info: String| {
log::info!("{}", info);
tracing::info!("{}", info);
Ok(())
});
methods.add_function("debug", |_, info: String| {
log::debug!("{}", info);
tracing::debug!("{}", info);
Ok(())
});
methods.add_function("warn", |_, info: String| {
log::warn!("{}", info);
tracing::warn!("{}", info);
Ok(())
});
methods.add_function("error", |_, info: String| {
log::error!("{}", info);
tracing::error!("{}", info);
Ok(())
});
}

View file

@ -68,7 +68,7 @@ impl PluginManager {
let path = PathBuf::from(i);
if !path.is_dir() {
// for loader dir, we need check first, because we need give a error log.
log::error!("Plugin loader: {:?} path is not a exists directory.", path);
tracing::error!("Plugin loader: {:?} path is not a exists directory.", path);
}
path_list.push((path, true));
}
@ -97,7 +97,7 @@ impl PluginManager {
&& !from_loader
{
// found same name plugin, intercept load
log::warn!(
tracing::warn!(
"Plugin {} has been intercepted. [mulit-load]",
info.name
);
@ -139,12 +139,12 @@ impl PluginManager {
}
}
Ok(false) => {
log::warn!(
tracing::warn!(
"Plugin init function result is `false`, init failed."
);
}
Err(e) => {
log::warn!("Plugin init failed: {e}");
tracing::warn!("Plugin init failed: {e}");
}
}
}
@ -158,7 +158,7 @@ impl PluginManager {
}
Err(_e) => {
let dir_name = plugin_dir.file_name().unwrap().to_str().unwrap();
log::error!("Plugin '{dir_name}' load failed.");
tracing::error!("Plugin '{dir_name}' load failed.");
}
}
}
@ -287,10 +287,10 @@ impl PluginManager {
let app_path = app_path();
let plugin_path = app_path.join("plugins");
if !plugin_path.is_dir() {
log::info!("📖 Start to init plugin library ...");
tracing::info!("📖 Start to init plugin library ...");
let url = "https://github.com/DioxusLabs/cli-plugin-library";
if let Err(err) = clone_repo(&plugin_path, url) {
log::error!("Failed to init plugin dir, error caused by {}. ", err);
tracing::error!("Failed to init plugin dir, error caused by {}. ", err);
}
}
plugin_path

View file

@ -39,7 +39,7 @@ pub(crate) async fn startup_with_platform<P: Platform + Send + 'static>(
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
tracing::error!("{}", err);
}
let file_map = Arc::new(Mutex::new(map));
@ -77,7 +77,7 @@ async fn serve<P: Platform + Send + 'static>(
) -> Result<()> {
let platform = RwLock::new(P::start(&config, serve)?);
log::info!("🚀 Starting development server...");
tracing::info!("🚀 Starting development server...");
// We got to own watcher so that it exists for the duration of serve
// Otherwise full reload won't work.
@ -258,7 +258,7 @@ impl DesktopPlatform {
) -> Result<Self> {
let (child, first_build_result) = start_desktop(config, serve.skip_assets, rust_flags)?;
log::info!("🚀 Starting development server...");
tracing::info!("🚀 Starting development server...");
// Print serve info
print_console_info(

View file

@ -89,7 +89,7 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
let mode = notify::RecursiveMode::Recursive;
if let Err(err) = watcher.watch(path, mode) {
log::warn!("Failed to watch path: {}", err);
tracing::warn!("Failed to watch path: {}", err);
}
}
@ -157,7 +157,7 @@ fn full_rebuild<F>(
}
Err(e) => {
*last_update_time = chrono::Local::now().timestamp();
log::error!("{:?}", e);
tracing::error!("{:?}", e);
}
}
}
@ -195,12 +195,12 @@ fn hotreload_files(
// If the file was not updated, we need to do a full rebuild
Ok(UpdateResult::NeedsRebuild) => {
log::trace!("Needs full rebuild because file changed: {:?}", path);
tracing::trace!("Needs full rebuild because file changed: {:?}", path);
*needs_full_rebuild = true;
}
// Not necessarily a fatal error, but we should log it
Err(err) => log::error!("{}", err),
Err(err) => tracing::error!("{}", err),
}
}
@ -214,7 +214,7 @@ fn hotreload_files(
} = FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
tracing::error!("{}", err);
}
*rsx_file_map = new_file_map;
@ -250,7 +250,7 @@ fn hotreload_file(
// If the extension is a backup file, or a hidden file, ignore it completely (no rebuilds)
if is_backup_file(path) {
log::trace!("Ignoring backup file: {:?}", path);
tracing::trace!("Ignoring backup file: {:?}", path);
return None;
}

View file

@ -145,9 +145,9 @@ pub fn print_console_info(
println!();
if options.warnings.is_empty() {
log::info!("{}\n", "A perfect compilation!".green().bold());
tracing::info!("{}\n", "A perfect compilation!".green().bold());
} else {
log::warn!(
tracing::warn!(
"{}",
format!(
"There were {} warning messages during the build. Run `cargo check` to see them.",

View file

@ -18,13 +18,13 @@ pub async fn hot_reload_handler(
let err = hotreload_loop(socket, state).await;
if let Err(err) = err {
log::error!("Hotreload receiver failed: {}", err);
tracing::error!("Hotreload receiver failed: {}", err);
}
})
}
async fn hotreload_loop(mut socket: WebSocket, state: HotReloadState) -> anyhow::Result<()> {
log::info!("🔥 Hot Reload WebSocket connected");
tracing::info!("🔥 Hot Reload WebSocket connected");
// update any rsx calls that changed before the websocket connected.
// These templates will be sent down immediately so the page is in sync with the hotreloaded version
@ -51,9 +51,9 @@ async fn hotreload_loop(mut socket: WebSocket, state: HotReloadState) -> anyhow:
msg = _rx => msg,
e = _socket => {
if let Some(Err(e)) = e {
log::info!("🔥 Hot Reload WebSocket Error: {}", e);
tracing::info!("🔥 Hot Reload WebSocket Error: {}", e);
} else {
log::info!("🔥 Hot Reload WebSocket Closed");
tracing::info!("🔥 Hot Reload WebSocket Closed");
}
break;
},
@ -69,7 +69,7 @@ async fn hotreload_loop(mut socket: WebSocket, state: HotReloadState) -> anyhow:
Message::Text(format!("reload-asset: {}", asset.display()))
}
HotReloadMsg::Shutdown => {
log::info!("🔥 Hot Reload WebSocket shutting down");
tracing::info!("🔥 Hot Reload WebSocket shutting down");
break;
}
}

View file

@ -57,7 +57,7 @@ pub async fn serve(
// generate dev-index page
Serve::regen_dev_page(&config, first_build_result.assets.as_ref())?;
log::info!("🚀 Starting development server...");
tracing::info!("🚀 Starting development server...");
// WS Reload Watching
let (reload_tx, _) = broadcast::channel(100);
@ -205,7 +205,7 @@ fn build_hotreload_filemap(config: &CrateConfig) -> HotReloadState {
let FileMapBuildResult { map, errors } = FileMap::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
tracing::error!("{}", err);
}
HotReloadState {

View file

@ -219,8 +219,8 @@ pub fn get_rustls_with_mkcert(web_config: &WebHttpsConfig) -> Result<(String, St
match cmd {
Err(e) => {
match e.kind() {
io::ErrorKind::NotFound => log::error!("mkcert is not installed. See https://github.com/FiloSottile/mkcert#installation for installation instructions."),
e => log::error!("an error occured while generating mkcert certificates: {}", e.to_string()),
io::ErrorKind::NotFound => tracing::error!("mkcert is not installed. See https://github.com/FiloSottile/mkcert#installation for installation instructions."),
e => tracing::error!("an error occured while generating mkcert certificates: {}", e.to_string()),
};
return Err("failed to generate mkcert certificates".into());
}

View file

@ -49,7 +49,7 @@ pub fn clone_repo(dir: &Path, url: &str) -> anyhow::Result<()> {
let res = cmd.arg("clone").arg(url).arg(dir_name).output();
if let Err(err) = res {
if ErrorKind::NotFound == err.kind() {
log::warn!("Git program not found. Hint: Install git or check $PATH.");
tracing::warn!("Git program not found. Hint: Install git or check $PATH.");
return Err(err.into());
}
}
@ -216,7 +216,7 @@ impl Tool {
let chunk = chunk_res.context("error reading chunk from download")?;
let _ = file.write(chunk.as_ref()).await;
}
// log::info!("temp file path: {:?}", temp_out);
// tracing::info!("temp file path: {:?}", temp_out);
Ok(temp_out)
}