Add logging to a Rust CLI by initializing env_logger in main or using tracing with a subscriber. For env_logger, add the dependency, initialize it, and use the log macros. For tracing, add the dependencies, initialize the subscriber, and use the tracing macros.
// Cargo.toml
[dependencies]
log = "0.4"
env_logger = "0.11"
// src/main.rs
use log::{info, error};
fn main() {
env_logger::init();
info!("Application started");
error!("Something went wrong");
}
// Cargo.toml
[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"
// src/main.rs
use tracing::{info, error, Level};
use tracing_subscriber;
fn main() {
tracing_subscriber::fmt()
.with_max_level(Level::INFO)
.init();
info!("Application started");
error!("Something went wrong");
}