use std::io::Result;
use std::io::Stderr;
use std::io::Write;
use clap::ColorChoice;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::filter::Directive;
use tracing_subscriber::fmt;
use mago_orchestrator::progress::GLOBAL_PROGRESS_MANAGER;
use super::should_use_colors;
pub fn initialize_logger(directive: impl Into<Directive>, env_var: impl Into<String>, color_choice: ColorChoice) {
let logger = fmt()
.with_env_filter(
EnvFilter::builder().with_default_directive(directive.into()).with_env_var(env_var.into()).from_env_lossy(),
)
.with_ansi(should_use_colors(color_choice))
.with_writer(LoggerWriter::stderr);
if cfg!(debug_assertions) {
logger.with_target(true).with_thread_names(true).init()
} else {
logger.without_time().with_target(false).with_thread_names(false).compact().init()
}
}
struct LoggerWriter<W: Write> {
writer: W,
}
impl LoggerWriter<Stderr> {
pub fn stderr() -> Self {
Self { writer: std::io::stderr() }
}
}
impl<W: Write> Write for LoggerWriter<W> {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
GLOBAL_PROGRESS_MANAGER.suspend(|| self.writer.write(buf))
}
fn flush(&mut self) -> Result<()> {
GLOBAL_PROGRESS_MANAGER.suspend(|| self.writer.flush())
}
}