|
| 1 | +//! Non-blocking file logger backed by a dedicated OS thread. |
| 2 | +//! |
| 3 | +//! Design: a bounded `mpsc::sync_channel` feeds a background thread that owns |
| 4 | +//! the file descriptor and writes through a 64 KB `BufWriter`. The hot path |
| 5 | +//! (`emit` / `emit_err`) does a single `try_send` — if the channel is full |
| 6 | +//! the message is silently dropped, so logging never blocks the proxy. |
| 7 | +//! |
| 8 | +//! Two entry points: `emit` (stdout) and `emit_err` (stderr). Both prepend |
| 9 | +//! an ISO-8601 timestamp and write to the log file when configured. When no |
| 10 | +//! log file is configured only the console stream is written (zero overhead |
| 11 | +//! from the file path — no channel, no allocation, no thread). |
| 12 | +
|
| 13 | +use std::fmt; |
| 14 | +use std::fs::OpenOptions; |
| 15 | +use std::io::{BufWriter, Write}; |
| 16 | +use std::sync::OnceLock; |
| 17 | +use std::sync::mpsc; |
| 18 | + |
| 19 | +/// Channel capacity — number of formatted log lines buffered before drops. |
| 20 | +const CHANNEL_CAP: usize = 4096; |
| 21 | + |
| 22 | +/// BufWriter capacity — bytes buffered before a syscall write. |
| 23 | +const BUF_CAP: usize = 64 * 1024; |
| 24 | + |
| 25 | +static FILE_TX: OnceLock<mpsc::SyncSender<String>> = OnceLock::new(); |
| 26 | + |
| 27 | +/// Initialise file logging. Call once at startup. |
| 28 | +/// If `path` is `None`, only console logging is active (the default). |
| 29 | +pub fn init(path: Option<&str>) { |
| 30 | + let Some(p) = path else { return }; |
| 31 | + |
| 32 | + let file = OpenOptions::new() |
| 33 | + .create(true) |
| 34 | + .append(true) |
| 35 | + .open(p) |
| 36 | + .unwrap_or_else(|e| panic!("[spiceio] failed to open log file {p}: {e}")); |
| 37 | + |
| 38 | + let (tx, rx) = mpsc::sync_channel::<String>(CHANNEL_CAP); |
| 39 | + |
| 40 | + std::thread::Builder::new() |
| 41 | + .name("spiceio-log".into()) |
| 42 | + .spawn(move || writer_loop(rx, file)) |
| 43 | + .expect("[spiceio] failed to spawn log thread"); |
| 44 | + |
| 45 | + FILE_TX.set(tx).ok(); |
| 46 | +} |
| 47 | + |
| 48 | +/// Background writer — drains the channel and flushes in batches. |
| 49 | +fn writer_loop(rx: mpsc::Receiver<String>, file: std::fs::File) { |
| 50 | + let mut w = BufWriter::with_capacity(BUF_CAP, file); |
| 51 | + while let Ok(line) = rx.recv() { |
| 52 | + let _ = w.write_all(line.as_bytes()); |
| 53 | + let _ = w.write_all(b"\n"); |
| 54 | + // Drain any queued messages before issuing the syscall flush. |
| 55 | + while let Ok(line) = rx.try_recv() { |
| 56 | + let _ = w.write_all(line.as_bytes()); |
| 57 | + let _ = w.write_all(b"\n"); |
| 58 | + } |
| 59 | + let _ = w.flush(); |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +/// Format a timestamp from `gettimeofday` into a fixed 24-byte ISO-8601 UTC |
| 64 | +/// string: `2026-04-02T16:09:34.123Z`. Uses a stack buffer — no allocation. |
| 65 | +fn timestamp(buf: &mut [u8; 24]) { |
| 66 | + #[repr(C)] |
| 67 | + struct Timeval { |
| 68 | + tv_sec: i64, |
| 69 | + tv_usec: i32, |
| 70 | + } |
| 71 | + |
| 72 | + unsafe extern "C" { |
| 73 | + fn gettimeofday(tp: *mut Timeval, tzp: *const std::ffi::c_void) -> i32; |
| 74 | + } |
| 75 | + |
| 76 | + let mut tv = Timeval { |
| 77 | + tv_sec: 0, |
| 78 | + tv_usec: 0, |
| 79 | + }; |
| 80 | + unsafe { |
| 81 | + gettimeofday(&mut tv, std::ptr::null()); |
| 82 | + } |
| 83 | + |
| 84 | + let secs = tv.tv_sec as u64; |
| 85 | + let millis = (tv.tv_usec / 1000) as u64; |
| 86 | + |
| 87 | + // Civil time from Unix epoch (Howard Hinnant algorithm) |
| 88 | + let days = secs / 86400; |
| 89 | + let rem = secs % 86400; |
| 90 | + let z = days + 719468; |
| 91 | + let era = z / 146097; |
| 92 | + let doe = z - era * 146097; |
| 93 | + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; |
| 94 | + let y = yoe + era * 400; |
| 95 | + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 96 | + let mp = (5 * doy + 2) / 153; |
| 97 | + let d = doy - (153 * mp + 2) / 5 + 1; |
| 98 | + let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| 99 | + let y = if m <= 2 { y + 1 } else { y }; |
| 100 | + |
| 101 | + let h = rem / 3600; |
| 102 | + let min = (rem % 3600) / 60; |
| 103 | + let s = rem % 60; |
| 104 | + |
| 105 | + // Write directly: "YYYY-MM-DDThh:mm:ss.mmmZ" |
| 106 | + buf[0] = b'0' + ((y / 1000) % 10) as u8; |
| 107 | + buf[1] = b'0' + ((y / 100) % 10) as u8; |
| 108 | + buf[2] = b'0' + ((y / 10) % 10) as u8; |
| 109 | + buf[3] = b'0' + (y % 10) as u8; |
| 110 | + buf[4] = b'-'; |
| 111 | + buf[5] = b'0' + ((m / 10) % 10) as u8; |
| 112 | + buf[6] = b'0' + (m % 10) as u8; |
| 113 | + buf[7] = b'-'; |
| 114 | + buf[8] = b'0' + ((d / 10) % 10) as u8; |
| 115 | + buf[9] = b'0' + (d % 10) as u8; |
| 116 | + buf[10] = b'T'; |
| 117 | + buf[11] = b'0' + ((h / 10) % 10) as u8; |
| 118 | + buf[12] = b'0' + (h % 10) as u8; |
| 119 | + buf[13] = b':'; |
| 120 | + buf[14] = b'0' + ((min / 10) % 10) as u8; |
| 121 | + buf[15] = b'0' + (min % 10) as u8; |
| 122 | + buf[16] = b':'; |
| 123 | + buf[17] = b'0' + ((s / 10) % 10) as u8; |
| 124 | + buf[18] = b'0' + (s % 10) as u8; |
| 125 | + buf[19] = b'.'; |
| 126 | + buf[20] = b'0' + ((millis / 100) % 10) as u8; |
| 127 | + buf[21] = b'0' + ((millis / 10) % 10) as u8; |
| 128 | + buf[22] = b'0' + (millis % 10) as u8; |
| 129 | + buf[23] = b'Z'; |
| 130 | +} |
| 131 | + |
| 132 | +/// Write a formatted message to **stdout** and (if configured) to the log file. |
| 133 | +#[inline] |
| 134 | +pub fn emit(args: fmt::Arguments<'_>) { |
| 135 | + let mut ts = [0u8; 24]; |
| 136 | + timestamp(&mut ts); |
| 137 | + let ts = unsafe { std::str::from_utf8_unchecked(&ts) }; |
| 138 | + println!("{ts} {args}"); |
| 139 | + if let Some(tx) = FILE_TX.get() { |
| 140 | + let _ = tx.try_send(format!("{ts} {args}")); |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +/// Write a formatted message to **stderr** and (if configured) to the log file. |
| 145 | +#[inline] |
| 146 | +pub fn emit_err(args: fmt::Arguments<'_>) { |
| 147 | + let mut ts = [0u8; 24]; |
| 148 | + timestamp(&mut ts); |
| 149 | + let ts = unsafe { std::str::from_utf8_unchecked(&ts) }; |
| 150 | + eprintln!("{ts} {args}"); |
| 151 | + if let Some(tx) = FILE_TX.get() { |
| 152 | + let _ = tx.try_send(format!("{ts} {args}")); |
| 153 | + } |
| 154 | +} |
0 commit comments