< 返回版块

mike 发表于 2022-02-21 10:29

traceing 库默认的是utc时区,日志打印出来都是8小时之前的,有没有大佬知道怎么更改traceing 库输出日志的时区,示例代码如下: 好像只要修改with_timer就可以了

 tracing_subscriber::fmt()
    .with_writer(mk_writer)
    .with_max_level(Level::TRACE)
    .with_timer(tracing_subscriber::fmt::time::time())
    .init();

我在源码里找到了这个例子 https://github.com/tokio-rs/tracing/blob/master/tracing-subscriber/src/fmt/time/time_crate.rs 110 行

看文档的提示好像按照下面的写法就可以了,但是这样写会报找不到 LocalTime in `fmt::time,


   use tracing_subscriber::fmt::{self, time::LocalTime};
   use time::macros::format_description;


   let timer = LocalTime::new(format_description!("[hour]:[minute]:[second]"));
    tracing_subscriber::fmt()
    .with_writer(mk_writer)
    .with_max_level(Level::TRACE)
    .with_timer(timer)
    .init();

这是我的 cargo.toml

[package]
name = "trace-example"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
axum = "0.4.5"
tokio = { version = "1.0", features = ["full"] }
tracing = "0.1.*"
tracing-subscriber = "0.3.8"
tracing-appender = "0.2"
tracing-log = "0.1.2"
log ="0.4.14"
tower-http = { version = "0.2.0", features = ["trace"] }
time = { version = "0.3", features = ["formatting", "macros"] }

有没有大佬指点一下

评论区

写评论
langzi.me 2022-02-21 13:41

let subscriber = FmtSubscriber::builder() .with_writer( std::io::stdout) .with_timer(UtcOffset::from_hms(8, 0, 0).unwrap()) .finish();

dlhxzb 2022-02-21 11:20

Struct tracing_subscriber::fmt::time::LocalTime

This is supported on crate feature fmt and crate feature std and unsound_local_offset and crate feature time and crate feature local-time only.

加features试试,类似

tracing-subscriber = { version = "0.3", features = ["local-time"] }

还有这个编译--cfg可能也得注意

Warning: The time crate must be compiled with --cfg unsound_local_offset in order to use local timestamps. When this cfg is not enabled, local timestamps cannot be recorded, and events will be logged without timestamps. Alternatively, OffsetTime can log with a local offset if it is initialized early.

0.2的时候用过ChronoLocal还没这么麻烦

1 2 共 22 条评论, 2 页