use std::time::Instant;
use crate::prelude::output::OutputFile;
use crate::routines::settings::Settings;
use anyhow::Result;
use tracing_subscriber::fmt::time::FormatTime;
use tracing_subscriber::fmt::{self};
use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
use tracing_subscriber::registry::Registry;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
pub fn setup_log(settings: &Settings) -> Result<()> {
let log_level = settings.log.level.as_str();
let env_filter = EnvFilter::new(log_level);
let timestamper = CompactTimestamp {
start: Instant::now(),
};
let subscriber = Registry::default().with(env_filter);
let outputfile = OutputFile::new(&settings.output.path, &settings.log.file)?;
let file_layer = fmt::layer()
.with_writer(outputfile.file)
.with_ansi(false)
.with_timer(timestamper.clone());
let stdout_layer = fmt::layer()
.with_writer(std::io::stdout)
.with_ansi(true)
.with_target(false)
.with_timer(timestamper.clone());
subscriber.with(file_layer).with(stdout_layer).init();
Ok(())
}
#[derive(Clone)]
struct CompactTimestamp {
start: Instant,
}
impl FormatTime for CompactTimestamp {
fn format_time(
&self,
w: &mut tracing_subscriber::fmt::format::Writer<'_>,
) -> Result<(), std::fmt::Error> {
let elapsed = self.start.elapsed();
let hours = elapsed.as_secs() / 3600;
let minutes = (elapsed.as_secs() % 3600) / 60;
let seconds = elapsed.as_secs() % 60;
write!(w, "{:02}h {:02}m {:02}s", hours, minutes, seconds)
}
}