Try tracing
(Jin Qing’s Column, Dec., 2021)
https://github.com/tokio-rs/tracing
Usage on github
Switch to tag tracing-0.1.29 first. The master’s examples can not build.
Subscriber is renaming to collector on master.
tracing::subscriber in 0.1.29 has been renamed to tracing::collect on master.
- In Applications
- In Libraries
- In async
The example is using tracing_subscriber::fmt, which can be configured by RUST_LOG env val.
By default, no log is output. Set RUST_LOG=info before running, and the log is:
Dec 25 10:23:11.200 INFO tracing_test: preparing to shave yaks number_of_yaks=3
Dec 25 10:23:11.203 INFO tracing_test: yak shaving completed. all_yaks_shaved=true
- span
- set_global_default()
- tracing::collect::with_default()
Usage of RUST_LOG.
RUST_LOG is defined in env_logger
- Default disabled except error
- RUST_LOG is comma-separated directives
- Directive form: example::log::target=level
- The log target is a prefix
- If target is ommitted, then all modules are set
- The level is “all” if ommitted
- off, error, warn, info, debug, trace
- The log target is a prefix
- Regex filter: error,hello=warn/[0-9]scopes
- For all directives
- Directive form: example::log::target=level
Usage on crates.io
It is slightly different from the github.
- Uses set_global_default()
- Explains some concepts
- span
- event
Span filter? [my_span]=info
Document
https://docs.rs/tracing/0.1.29/tracing/
The document is much more detailed than github and crates.io.
Code examples
Run example:
cargo run --example counters
Write to file
fmt-multiple-writers:
- Change to write to current dir
tracing_appender::rolling::hourly(".", ...
- Do not write ANSI color to file
.with(fmt::Layer::new().with_writer(non_blocking).with_ansi(false));
Dynamic level
tower-load
- with_filter_reloading() -> reload handl -> handle.reload(new_filter)
- new filter is send through http
https://github.com/tokio-rs/tracing/issues/1629
tracing_subscriber::reload
They use the same tracing_subscriber::reload::Handle::reload()
Filters and Layers
https://docs.rs/tracing-subscriber/0.3.4/tracing_subscriber/layer/index.html#filtering-with-layers
Reload from config file
It is desired to reconfigure the log filter in the runtime by SIGHUP, or watch configure file change.
It can use notify crate to watch file.
use anyhow::{anyhow, Context as _, Result};
use hotwatch::{Event, Hotwatch};
use std::{fs, thread, time::Duration};
use tracing::{debug, info, warn, Subscriber};
use tracing_subscriber::{reload::Handle, EnvFilter};
const CFG: &str = "cfg.txt";
fn main() -> Result<()> {
let builder = tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.with_filter_reloading();
let handle = builder.reload_handle();
builder
.try_init()
.map_err(|e| anyhow!(e))
.context("failed to init subscriber builder")?;
tracing::info!("Before reload");
reload_cfg(handle.clone());
let mut hotwatch = Hotwatch::new().context("hotwatch failed to initialize!")?;
hotwatch
.watch(CFG, move |event: Event| {
if let Event::Write(_) = event {
reload_cfg(handle.clone());
}
})
.context("failed to watch file")?;
for i in 0..999 {
info!(i);
thread::sleep(Duration::from_secs(1));
}
Ok(())
}
fn reload_cfg<S: Subscriber + 'static>(handle: Handle<EnvFilter, S>) {
let res = try_reload_cfg(handle);
match res {
Ok(_) => debug!("reload cfg OK"),
Err(e) => warn!("reload cfg error: {:?}", e),
}
}
fn try_reload_cfg<S: Subscriber + 'static>(handle: Handle<EnvFilter, S>) -> Result<()> {
let contents = fs::read_to_string(CFG).context("something went wrong reading the file")?;
let contents = contents.trim();
debug!("reload cfg: {:?}", contents);
let new_filter = contents
.parse::<EnvFilter>()
.map_err(|e| anyhow!(e))
.context("failed to parse env filter")?;
handle.reload(new_filter).context("handle reload error")
}
How to new a Subscriber with tracing-subscriber
- SubscriberBuilder:
- fmt().init()
- with_env_filter()
- with_filter_reloading()
- reload_handle()
- finish() to get a Subscriber and then add a file Layer?
- https://github.com/tokio-rs/tracing/issues/971
- Registry:
- registry().with…()
- Currently, the [
Registry] type provided by this crate is the only [Subscriber] implementation capable of participating in per-layer filtering.
- FmtSubscriber
- new it manually
- need SubscriberBuilder to configure
这篇博客介绍了如何使用tracing库在不同的应用场景中进行日志记录,包括设置环境变量RUST_LOG来配置日志级别,使用tracing_subscriber::fmt进行日志输出,并展示了如何动态地通过reload函数更新日志过滤器。文章还提到了tracing的span、event概念,以及如何将日志写入文件并避免ANSI颜色。此外,还讨论了如何通过监听文件变化实时重载日志过滤规则。
377

被折叠的 条评论
为什么被折叠?



