How to Add Logging to Rust CLI Applications (env_logger, tracing)

Cli
Initialize env_logger or tracing-subscriber in main and use their respective macros to log events in your Rust CLI.

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");
}