如何在 Rust 中使用 env_logger crate 在 IST 时区打印日志?



下面的最小示例。下面的代码以 UTC 时区打印日志。如何以 IST 时区打印日志?

use std::env;
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "proxy=debug,common=debug");
}
env_logger::Builder::from_default_env()
.default_format_timestamp_nanos(true)
.init();

恐怕做不到。在引擎盖下,env_logger使用humantime箱来格式化各种时间戳。例如,启用纳秒精度,以便将实现委托给humantime::format_rfc3339_nanos。其文件如下:

该值始终为 UTC,并忽略系统时区。

如果其他人正在寻找这个,它实际上是可能的:

use chrono::Utc;
use env_logger::Builder;
use log::LevelFilter;
use std::io::Write;
fn main() {
Builder::new()
.format(|buf, record| {
let dt = Utc::now(); // Current time in UTC
// Convert to Indian Standard Time (UTC+05:30)
let ist = dt.with_timezone(&chrono::FixedOffset::east_opt(5 * 3600 + 30 * 60).unwrap()); 

writeln!(
buf,
"{} [{}] - {}",
ist.format("%Y-%m-%dT%H:%M:%S"),
record.level(),
record.args()
)
})
.filter(None, LevelFilter::Info)
.init();
log::warn!("warn");
log::info!("info");
log::debug!("debug");
}

这将输出:

2023-08-27T08:27:28 [WARN] - warn
2023-08-27T08:27:28 [INFO] - info

源: https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log.html#include-timestamp-in-log-messages

最新更新