54 lines
1.3 KiB
Rust
54 lines
1.3 KiB
Rust
use tracing::Level;
|
|
use tracing_subscriber::{Layer as _, layer::SubscriberExt as _, util::SubscriberInitExt as _};
|
|
|
|
pub const DEFAULT_LOG_LEVEL: Level = if cfg!(debug_assertions) {
|
|
Level::DEBUG // debug builds
|
|
} else {
|
|
Level::INFO // release builds
|
|
};
|
|
|
|
fn level_to_index(level: Level) -> u8 {
|
|
match level {
|
|
Level::TRACE => 0,
|
|
Level::DEBUG => 1,
|
|
Level::INFO => 2,
|
|
Level::WARN => 3,
|
|
Level::ERROR => 4,
|
|
}
|
|
}
|
|
|
|
fn index_to_level(index: u8) -> Level {
|
|
match index {
|
|
0 => Level::TRACE,
|
|
1 => Level::DEBUG,
|
|
2 => Level::INFO,
|
|
3 => Level::WARN,
|
|
4.. => Level::ERROR,
|
|
}
|
|
}
|
|
|
|
fn level_from_verbosity(verbosity: u8) -> Level {
|
|
index_to_level(level_to_index(DEFAULT_LOG_LEVEL).saturating_sub(verbosity))
|
|
}
|
|
|
|
pub fn init_tracing(verbosity: u8) -> anyhow::Result<()> {
|
|
let terminal_layer = tracing_subscriber::fmt::layer()
|
|
.without_time()
|
|
.compact()
|
|
.boxed();
|
|
|
|
let level = level_from_verbosity(verbosity);
|
|
|
|
tracing_subscriber::registry()
|
|
.with(terminal_layer)
|
|
.with(
|
|
tracing_subscriber::EnvFilter::builder()
|
|
.with_default_directive(level.into())
|
|
.from_env()?,
|
|
)
|
|
.init();
|
|
|
|
tracing::info!("logging with level {level}");
|
|
|
|
Ok(())
|
|
}
|