以下最小示例
#[macro_use]
extern crate log;
extern crate env_logger;
fn main() {
std::env::set_var("MY_LOG_LEVEL", "info");
env_logger::init_from_env("MY_LOG_LEVEL");
info!("hi");
}
输出:
INFO 2018-02-18T09:59:20Z: playground: hi
我想使用不同的格式(
"%Y-%m-%d %H:%M:%S%.3f"
):
INFO 2018-02-18 09:59:20.123: playground: hi
我怎样才能实现这个目标?
现在通过
env_logger = "0.10"
可以实现这一点。
要么
env_logger::builder()
// setting this to None disables the timestamp
.format_timestamp(Some(env_logger::TimestampPrecision::Millis))
.init();
或
env_logger::builder()
//.format_timestamp_secs()
.format_timestamp_millis()
//.format_timestamp_micros()
//.format_timestamp_nanos()
.init();
目前这是不可能的。
Formatter
更改记录消息的格式,但此格式化程序为您提供日志消息的时间戳作为 Timestamp
。 Timestamp
仅实现了Debug
和Display
,没有额外的方法。该文档没有提到如何配置日期的显示方式。它只提到该类代表“一个RFC3339格式的时间戳”。该 RFC 定义了显示日期的方式。您想要的格式与 RFC 不兼容(最重要的是,它缺少时区,请不要在没有时区的情况下记录日期时间)。
RFC 确实允许比 crate 当前使用的精度更高。此功能在最近标题为“使时间戳格式更紧凑”的拉取请求中被删除。在我看来,提高精度有时很有用,您可以提出一个问题来要求 Timestamp
允许该选项。 RFC 也不允许省略日期和时间之间的
T
。查看两个特征(和
Display
)的实现表明,表示确实是固定的。
env_logger
中的日期,如果你真的想的话,可以选择你自己的日期。我不确定那会有多糟糕。
use chrono::Local;
use env_logger::Builder;
use log::LevelFilter;
use std::io::Write;
fn main() {
Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{} {}: {}",
record.level(),
//Format like you want to: <-----------------
Local::now().format("%Y-%m-%d %H:%M:%S%.3f"),
record.args()
)
})
.filter(None, LevelFilter::Info)
.init();
log::warn!("warn");
log::info!("info");
log::debug!("debug");
}
更多信息: