You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改env_logger的时间戳格式为"%Y-%m-%d %H:%M:%S%.3f"?

Customizing env_logger Timestamp Format to "%Y-%m-%d %H:%M:%S%.3f"

Hey there! Let me walk you through exactly how to tweak env_logger's timestamp output to match your desired format. The key here is using env_logger's builder API, which lets you take full control over how log lines are structured.

Step 1: Update Your Dependencies

First, make sure your Cargo.toml has the right crates. We'll use env_logger for logging, log for the logging macros, and chrono to handle the precise timestamp formatting (it makes this way simpler than rolling your own):

[dependencies]
env_logger = "0.10"
log = "0.4"
chrono = "0.4"

Step 2: Full Working Example

Instead of using the basic env_logger::init(), we'll build a custom logger instance with our timestamp format. Here's a complete, runnable snippet:

use env_logger::{Builder, Env};
use log::{info, warn};
use std::fmt::Write;

fn main() {
    // Set up the logger with custom formatting
    Builder::from_env(Env::default().default_filter_or("info"))
        .format(|buf, record| {
            // Grab the current local time and format it to your spec
            let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
            // Build the final log line
            writeln!(
                buf,
                "[{}] {}: {}",
                timestamp,
                record.level(),
                record.args()
            )
        })
        .init();

    // Test out the logger
    info!("This is an info message with your custom timestamp");
    warn!("This warning uses the same timestamp format too!");
}

Quick Breakdown of the Key Bits

  • Builder::from_env(...): This keeps the standard RUST_LOG environment variable behavior (so you can still filter logs via the shell), with a default filter of "info" if RUST_LOG isn't set.
  • The format closure: This is where the magic happens. We use chrono::Local::now() to get the current time, then format() with your exact timestamp string to get that precise YYYY-MM-DD HH:MM:SS.sss output.
  • writeln!: Puts all the pieces together—timestamp, log level, and your message—into a clean log line.

Alternative: No Chrono Dependency (If You Prefer)

If you don't want to add chrono, you can use the time crate instead to handle formatting. Here's a quick version of that:

use env_logger::{Builder, Env};
use log::{info, warn};
use std::fmt::Write;
use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    Builder::from_env(Env::default().default_filter_or("info"))
        .format(|buf, record| {
            let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
            let secs = now.as_secs();
            let millis = now.subsec_millis();
            
            // Convert seconds to a human-readable datetime, then append millis
            let dt = time::OffsetDateTime::from_unix_timestamp(secs as i64).unwrap();
            let timestamp = format!("{}:{:03}", dt.format("%Y-%m-%d %H:%M:%S"), millis);
            
            writeln!(
                buf,
                "[{}] {}: {}",
                timestamp,
                record.level(),
                record.args()
            )
        })
        .init();

    info!("Manual timestamp formatting without chrono");
}

For this, swap chrono with time in your Cargo.toml:

[dependencies]
time = "0.3"

Either approach will give you the timestamp format you're after—logs will look like [2024-05-20 15:42:18.765] INFO: Your log message here.


内容的提问来源于stack exchange,提问作者Tobias Hermann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:52:57