What is the log library for Rust?
The log library is a standard abstraction for logging in the Rust ecosystem. It provides a lightweight facade that allows developers to write code that generates logs without being tied to a specific logger implementation (e.g., env_logger, simple_logger, or slog). It is analogous to popular logging libraries in Python, but with a focus on performance and memory safety.
Why is the log library needed?
The main goal of log is to separate log generation from log processing. You can use the info!, warn!, error! macros in your code, and later, by connecting one of the backends (e.g., env_logger), redirect the output to the console, a file, or a monitoring system. This is especially useful for:
- Debugging complex systems
- Monitoring production applications
- Creating libraries that should not dictate the logging method to the user
Installation
Add to Cargo.toml:
[dependencies]log = "0.4"env_logger = "0.10" # for console outputThen run cargo build.
Main Features
- Logging macros:
error!,warn!,info!,debug!,trace!— with support for string formatting like inprintln!. - Filtering levels: you can set a minimum level (e.g., only errors) via the
RUST_LOGenvironment variable. - Extensibility: support for custom loggers through the
Logtrait. - Safety: logs do not affect performance if the level is disabled.
Rust Code Example
use log::{info, warn, error};
fn main() { // Initialize the logger (env_logger) env_logger::init();
let user = "Alice"; let status = 200;
info!("User {} logged into the system", user); warn!("Response status: {} — possibly stale cache", status); error!("Failed to connect to the database: {}", "timeout");}Run with RUST_LOG=info cargo run to see all messages at the info level and above.
When to use
The log library is ideal for:
- Any Rust application that needs a standard logging system (CLI, servers, utilities).
- Libraries — so the user can choose the backend themselves.
- Projects migrating from Python: the concept is similar to
logging.getLogger().
Avoid log if you need asynchronous file writing or structured JSON logs — in such cases, tracing or slog are better suited.