Logging in Rust
In this lesson, you will learn how logging works in Rust and how to record important information while your program is running.
Logging is essential for debugging, monitoring, and maintaining applications in production environments.
What Is Logging?
Logging is the practice of recording messages that describe what a program is doing at runtime.
Unlike printing values with println!, logging provides structured
levels such as informational messages, warnings, and errors.
Why Logging Is Important
Logging helps developers:
- Debug issues without stopping the program
- Understand application behavior in production
- Track errors and warnings
- Monitor performance and usage
Rust encourages structured and configurable logging.
The log Crate
Rust provides a standard logging facade through the log crate.
It defines logging macros but does not decide where logs are written. That responsibility belongs to logging implementations.
Add the following dependencies to your Cargo.toml file:
[dependencies]
log = "0.4"
env_logger = "0.10"
Initializing the Logger
Before using logging macros, you must initialize the logger.
use env_logger;
fn main() {
env_logger::init();
}
This setup enables logging output to the console.
Logging Levels
Rust logging supports multiple levels of severity:
error!– critical failureswarn!– potential problemsinfo!– general informationdebug!– debugging detailstrace!– very detailed output
Using Logging Macros
You can log messages using macros provided by the log crate.
use log::{info, warn, error};
fn main() {
env_logger::init();
info!("Application started");
warn!("Low disk space");
error!("Unable to open file");
}
Messages appear based on the configured log level.
Setting the Log Level
The log level can be controlled using the RUST_LOG environment variable.
RUST_LOG=info cargo run
Only messages at the specified level or higher will be displayed.
Logging Structured Data
Logging macros support formatted output.
let user_id = 42;
info!("User {} logged in", user_id);
This makes logs more readable and informative.
Logging Errors
Errors can be logged along with contextual information.
match std::fs::read_to_string("config.txt") {
Ok(data) => info!("Config loaded"),
Err(e) => error!("Failed to read config: {}", e),
}
Best Practices for Logging
- Use appropriate log levels
- Avoid logging sensitive data
- Prefer logging over excessive printing
- Keep log messages clear and concise
📝 Practice Exercises
Exercise 1
Initialize logging in a Rust program and log an info message.
Exercise 2
Log a warning and an error message.
Exercise 3
Use formatted logging to include variable values.
✅ Practice Answers
Answer 1
env_logger::init();
log::info!("Logger initialized");
Answer 2
log::warn!("This is a warning");
log::error!("This is an error");
Answer 3
let count = 5;
log::info!("Processed {} records", count);
What’s Next?
In the next lesson, you will learn about Performance Optimization in Rust and how to write fast, efficient applications.