use std::io::{IsTerminal, Write};
use crate::bus::TraceSubscriber;
use crate::event::RosaceTrace;
pub struct LogConsoleSubscriber {
color: bool,
start: web_time::Instant,
}
impl LogConsoleSubscriber {
pub fn new() -> Self {
Self {
color: std::io::stdout().is_terminal(),
start: web_time::Instant::now(),
}
}
pub fn with_color(mut self, on: bool) -> Self {
self.color = on;
self
}
}
impl Default for LogConsoleSubscriber {
fn default() -> Self {
Self::new()
}
}
impl TraceSubscriber for LogConsoleSubscriber {
fn on_trace(&self, event: &RosaceTrace) {
let RosaceTrace::Log { level, target, message, timestamp } = event else {
return; };
let secs = timestamp.saturating_duration_since(self.start).as_secs_f64();
let line = if self.color {
format!(
"\x1b[2m{secs:8.3}\x1b[0m {}{}\x1b[0m \x1b[2m{target}\x1b[0m {message}\n",
level.ansi(),
level.label(),
)
} else {
format!("{secs:8.3} {} {target} {message}\n", level.label())
};
let out = std::io::stdout();
let _ = out.lock().write_all(line.as_bytes());
}
}