pub use tracing;
use tracing_subscriber::fmt::time::LocalTime;
use tracing_subscriber::{fmt, EnvFilter};
pub use tracing::{debug, error, info, warn};
#[derive(Debug, Clone, Copy)]
pub enum LogLevel {
ERROR,
WARN,
INFO,
DEBUG,
TRACE,
}
impl From<LogLevel> for tracing::Level {
fn from(level: LogLevel) -> Self {
match level {
LogLevel::ERROR => tracing::Level::ERROR,
LogLevel::WARN => tracing::Level::WARN,
LogLevel::INFO => tracing::Level::INFO,
LogLevel::DEBUG => tracing::Level::DEBUG,
LogLevel::TRACE => tracing::Level::TRACE,
}
}
}
pub fn init_log(level: LogLevel) {
let filter = EnvFilter::builder()
.with_default_directive(tracing::Level::from(level).into())
.from_env_lossy();
use time::format_description::parse;
use time::UtcOffset;
let format = parse("[year]-[month padding:zero]-[day padding:zero] [hour]:[minute]:[second]")
.expect("Failed to parse time format");
let offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
let timer = fmt::time::OffsetTime::new(offset, format);
tracing_subscriber::fmt()
.with_env_filter(filter)
.compact()
.with_timer(timer) .with_target(true)
.with_file(true)
.with_line_number(true)
.with_ansi(true)
.init();
}
pub fn init_with_filter(env_filter: &str, include_ansi: bool) {
fmt()
.with_env_filter(EnvFilter::new(env_filter))
.with_target(true)
.with_file(true)
.with_line_number(true)
.with_timer(fmt::time::LocalTime::rfc_3339())
.with_ansi(include_ansi)
.init()
}
pub fn init_with_config<F>(config_fn: F)
where
F: Fn(fmt::SubscriberBuilder) -> fmt::SubscriberBuilder,
{
let subscriber = fmt::Subscriber::builder();
let configured_subscriber = config_fn(subscriber);
configured_subscriber.init()
}
#[cfg(test)]
mod tests {
#[test]
fn test_tracing_reexport() {
use crate::log::tracing;
tracing::trace!("Test trace message"); assert!(true);
}
#[test]
fn test_init_function() {
let result = std::panic::catch_unwind(|| {
crate::log::init();
});
assert!(result.is_ok() || result.is_err());
}
}