//! Dev text log: a [`LogSink`] that writes wall-clock stamped lines. //! //! The logger is a diagnostic observer. It is off unless `--dev`, `--log` or a //! matching environment variable asks for it, and it never feeds data back into //! the simulation. The app installs [`DevLogSink`] into the `fabrilis_core::log` //! facade before the startup banner, so every record goes through one filter. //! //! Line shape: `unix_s level target message`. pub(crate) mod startup; #[cfg(test)] mod tests; use std::fs::{File, OpenOptions}; use std::io::{self, Write}; use std::path::Path; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use fabrilis_core::log::{Level, LogSink, Record}; use crate::runtime::metrics::{FrameDetail, Stats}; /// How often a metrics summary line is written, seconds. const SUMMARY_INTERVAL_SECONDS: u64 = 1; /// A dev log file, truncated or created when opened. /// /// The facade already applies the level filter, so the log writes every record /// it receives. pub(crate) struct DevLog { file: File, last_summary: Instant, } impl DevLog { /// Creates or opens the file, truncating it unless `append` is set. #[allow( clippy::disallowed_methods, reason = "the dev log is a wall-clock observer of the app loop" )] pub(crate) fn open(path: &Path, append: bool) -> io::Result { let file = OpenOptions::new() .create(true) .write(true) .append(append) .truncate(!append) .open(path)?; Ok(Self { file, last_summary: Instant::now(), }) } /// Writes one line and flushes it, so the log survives a crash. pub(crate) fn write(&mut self, level: Level, target: &str, message: &str) -> io::Result<()> { let line = format_line(unix_now(), level, target, message); writeln!(self.file, "{line}")?; self.file.flush() } /// Whether the once-per-second metrics summary is due. #[allow( clippy::disallowed_methods, reason = "the dev log is a wall-clock observer of the app loop" )] pub(crate) fn summary_due(&mut self) -> bool { if self.last_summary.elapsed().as_secs() < SUMMARY_INTERVAL_SECONDS { return false; } self.last_summary = Instant::now(); true } } /// [`LogSink`] adapter over the shared dev log file. pub(crate) struct DevLogSink { log: Arc>, } impl DevLogSink { pub(crate) fn new(log: Arc>) -> Self { Self { log } } } impl LogSink for DevLogSink { fn log(&self, record: &Record<'_>) { let message = record.message.to_string(); let mut log = lock(&self.log); if let Err(error) = log.write(record.level, record.target, &message) { eprintln!("fabrilis: dev log write failed: {error}"); } } } /// Locks the shared dev log, recovering a poisoned mutex without panicking. pub(crate) fn lock(log: &Mutex) -> MutexGuard<'_, DevLog> { match log.lock() { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), } } /// Formats one log line without the trailing newline. pub(crate) fn format_line(unix_s: f64, level: Level, target: &str, message: &str) -> String { format!("{unix_s:.3} {level} {target} {message}") } /// One-line metrics summary written about once per second. pub(crate) fn summary(stats: &Stats) -> String { format!( "fps={:.1} tps={:.1} frame={:.2}/{:.2} ms physics={:.2}/{:.2} ms render={:.2} ms rtf={:.2} cpu={:.1}% load1={:.2} rss={:.1} MB", stats.fps, stats.tps, stats.frame_avg_ms, stats.frame_max_ms, stats.physics_avg_ms, stats.physics_max_ms, stats.render_avg_ms, stats.rtf, stats.cpu_percent, stats.load_1m, stats.rss_mb, ) } /// One-line description of a frame that exceeded its budget. /// /// The phase fields tell a slow simulation apart from a slow renderer, an /// expensive overlay or title update, and the `/proc` sampling cost. A frame /// with small phases but a large `frame_ms` was delayed outside the app. pub(crate) fn spike(frame: u64, detail: &FrameDetail, trigger: &str) -> String { format!( "frame={frame} frame_ms={:.2} physics_step_ms={:.3} render_ms={:.2} overlay_ms={:.2} title_ms={:.2} metrics_us={:.0} steps={} trigger={trigger}", detail.frame_ms, detail.physics_step_ms, detail.render_ms, detail.overlay_ms, detail.title_ms, detail.metrics_us, detail.steps, ) } /// Wall-clock seconds since the Unix epoch, as a float. #[allow( clippy::disallowed_methods, reason = "the dev log is a wall-clock observer of the app loop" )] fn unix_now() -> f64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0.0, |elapsed| elapsed.as_secs_f64()) }