use std::path::Path;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::{
fmt::{self, time::ChronoUtc},
prelude::*,
EnvFilter,
};
pub fn init_logging(log_dir: impl AsRef<Path>, log_prefix: &str) -> anyhow::Result<()> {
let log_dir_path = log_dir.as_ref();
std::fs::create_dir_all(log_dir_path)?;
let file_appender = RollingFileAppender::builder()
.rotation(Rotation::DAILY)
.filename_prefix(log_prefix)
.build(log_dir_path)?;
let (file_writer, _guard) = tracing_appender::non_blocking(file_appender);
let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| {
EnvFilter::new("capnweb=debug,tower_http=debug,axum=debug,hyper=debug,warn")
});
let console_layer = fmt::layer()
.with_target(true)
.with_thread_ids(true)
.with_timer(ChronoUtc::rfc_3339())
.with_writer(std::io::stderr);
let file_layer = fmt::layer()
.with_target(true)
.with_thread_ids(true)
.with_timer(ChronoUtc::rfc_3339())
.with_ansi(false) .with_writer(file_writer);
tracing_subscriber::registry()
.with(env_filter)
.with(console_layer)
.with(file_layer)
.init();
std::mem::forget(_guard);
tracing::info!("Logging initialized with file output to {:?}", log_dir_path);
Ok(())
}
pub fn init_test_logging() {
let _ = tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("capnweb=trace,debug")),
)
.try_init();
}