Error logging is essential for identifying and troubleshooting issues in a software application. In this article, we’ll create a Rust CLI tool that logs system errors to a file. This tool will listen for system events and write error messages to a log file, providing a useful record of any problems encountered during runtime.
Step 1: Set Up Your Project
First, create a new Rust project:
cargo new error_logger --bin
cd error_logger
This initializes a basic project structure with src/main.rs
, where we will add our logic to log system errors.
Step 2: Add Dependencies
We’ll use the chrono
crate for handling timestamps and log
along with env_logger
for logging. Add these dependencies to your Cargo.toml
:
[dependencies]
chrono = "0.4"
log = "0.4"
env_logger = "0.9"
chrono
will allow us to add timestamps to our log entries, and log
along with env_logger
provides a flexible logging framework.
Step 3: Implement the Logging Functionality
Now we’ll implement the logging logic. We’ll set up a basic logger and write error messages to a file, each with a timestamp. Here's the code for main.rs
:
use chrono::Local;
use log::{info, error};
use std::fs::OpenOptions;
use std::io::Write;
use std::process;
fn setup_logger() {
env_logger::builder().target(env_logger::Target::Stdout).init();
}
fn log_error(message: &str) -> std::io::Result<()> {
let timestamp = Local::now().to_rfc3339();
let log_message = format!("[{}] ERROR: {}\n", timestamp, message);
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open("error_log.txt")?;
file.write_all(log_message.as_bytes())?;
Ok(())
}
fn main() {
setup_logger();
// Simulating system errors
if let Err(e) = log_error("Failed to connect to database") {
error!("Error logging failed: {}", e);
process::exit(1);
}
info!("System started successfully.");
}
In this code:
-
log_error
writes an error message along with a timestamp toerror_log.txt
. -
setup_logger
configures the logger to output logs to the standard output (stdout). - The
main
function simulates an error and logs it.
Step 4: Build and Test the Tool
Now, build and run the tool:
cargo build --release
./target/release/error_logger
The tool will log an error message like the following:
[2025-05-12T14:56:00+00:00] ERROR: Failed to connect to database
Check the contents of error_log.txt
:
[2025-05-12T14:56:00+00:00] ERROR: Failed to connect to database
Use Case Scenario
This tool is ideal for system administrators or developers who need to capture and record system errors in real-time. For example, when an application fails to connect to a database or experiences an unexpected exception, the tool will automatically log the error to a file. Over time, this creates a valuable record of issues that can be reviewed to improve system reliability.
✅ Pros and ❌ Cons of Using Rust for CLI Tools
✅ Pros:
- ⚡ Rust is fast and efficient, making it ideal for logging system events in real time.
- 📂 The tool writes logs to a file, which can be analyzed later for troubleshooting.
- 🧑💻 Using
log
withenv_logger
provides a flexible and configurable logging system. - 🧪 Rust’s error handling and type safety reduce the likelihood of crashes.
❌ Cons:
- 📘 Rust has a steeper learning curve compared to scripting languages like Python.
- 🧩 The log system is fairly simple, and advanced logging features (like remote logging) would require more setup.
Summary
In this article, we built a Rust CLI tool for logging system errors with timestamps. We used log
and env_logger
to set up a flexible logging system and wrote error messages to a log file. This tool is perfect for tracking issues in applications and can be customized to handle different types of logs.
For a deeper dive into building robust Rust command-line tools, check out my 15-page guide:
Crafting Command-Line Tools in Rust: A Practical Guide to Building Fast, Reliable Utilities — just $5.
If this was helpful, you can also support me here: Buy Me a Coffee ☕
Top comments (0)