Of course! In env_logger, you can control the entire format of a log message, including the timestamp, by using the Builder and its format method.
Here's how to toggle the timestamp on and off.
1. Toggling Timestamps OFF (The Simple Way)
The easiest way to remove the timestamp is to define a custom format that doesn't include it.
You create a Builder, provide a formatting closure to the .format() method, and then initialize the logger.
// main.rs
use std::io::Write;
use log::{info, warn, error};
fn main() {
env_logger::Builder::new()
// Override the default format
.format(|buf, record| {
// This format doesn't include a timestamp
writeln!(buf, "[{}] - {}", record.level(), record.args())
})
.filter(None, log::LevelFilter::Info) // Set a default log level
.init();
info!("This is an informational message.");
warn!("This is a warning.");
error!("This is a critical error!");
}
To run this:
-
Add dependencies to Cargo.toml:
[dependencies]
log = "0.4"
env_logger = "0.11" # Use the latest version
-
Run the code:
cargo run
Output (No Timestamp):
[INFO] - This is an informational message.
[WARN] - This is a warning.
[ERROR] - This is a critical error!
2. Re-enabling Timestamps (or Replicating the Default Format)
If you've customized your format but want to add the timestamp back in (or create a format similar to the default), you can use the Formatter's timestamp() method within the closure.
This example shows how to build a custom format that does include the timestamp, a colored level, and the message. This demonstrates how you have full control.
// main.rs
use std::io::Write;
use env_logger::Builder;
use log::{info, warn, error};
fn main() {
let mut builder = Builder::new();
builder
.format(|buf, record| {
// buf is a `Formatter`, which has a `timestamp()` method
writeln!(
buf,
"{} [{}] - {}",
buf.timestamp(),
record.level(),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();
info!("A message with a custom timestamp format.");
warn!("Another message, also with a timestamp.");
}
Output (Timestamp ON):
2023-10-27T10:30:00.123456Z [INFO] - A message with a custom timestamp format.
2023-10-27T10:30:00.123457Z [WARN] - Another message, also with a timestamp.
Explanation of the format Closure
The format method takes a closure with the following signature:
fn(formatter: &mut Formatter, record: &Record) -> std::io::Result<()>
-
formatter: &mut Formatter: This is a buffer you write your formatted log message into. It's a wrapper around &mut dyn Write and provides helpful methods like:
formatter.timestamp(): Gets a pre-formatted timestamp string.
formatter.timestamp_millis(), formatter.timestamp_seconds(), etc.: For different precisions.
formatter.style(): For adding colors and styles (bold, underline) to your output.
formatter.default_level_style(): A convenient way to get the default color for a log level.
-
record: &Record: This struct contains all the information about the log event itself:
record.level(): The Level of the message (e.g., Info, Warn).
record.args(): The actual log message payload.
record.target(): The module path where the log originated (e.g., my_app::main).
record.file() and record.line(): The source file and line number (if available).
Complete Example: Customization with Colors
Here is a more advanced example that mimics the default env_logger style but gives you the power to remove or add the timestamp as you see fit.
// main.rs
use std::io::Write;
use env_logger::Builder;
use log::{info, warn, error, Level};
fn main() {
let mut builder = Builder::from_default_env();
builder.format(|buf, record| {
// Decide here if you want the timestamp
let with_timestamp = true;
let level_style = buf.default_level_style(record.level());
if with_timestamp {
writeln!(
buf,
"{} {} [{}] {}",
buf.timestamp_micros(), // Precise timestamp
level_style.value(record.level()),
record.target(),
record.args()
)
} else {
writeln!(
buf,
"{} [{}] {}",
level_style.value(record.level()),
record.target(),
record.args()
)
}
}).init();
info!("This is info!");
warn!("This is a warning!");
error!("This is an error!");
}
In this final example, you can simply change let with_timestamp = true; to false to toggle the timestamp off without changing anything else about your custom, colored format.