Skip to main content

robonix_scribe/
format.rs

1//! Console formatter — logcat-style single-line human-readable output.
2//!
3//! Format: `MM-DD HH:MM:SS.sss  L tag       msg`
4//!
5//! Level is a single character (D/I/W/E).  Tag is padded to 24 characters
6//! left-aligned.  Timestamp is local time derived from the nanosecond
7//! UNIX-epoch `ts` field.
8
9use crate::{CLOCK_ERROR_NOTE, Level, LogRecord};
10use std::io::{self, IsTerminal, Write};
11
12/// Tag display width in console output (left-aligned, space-padded).
13const TAG_WIDTH: usize = 24;
14
15pub(crate) fn write_clock_error(
16    level: Level,
17    tag: &str,
18    msg: &str,
19    error: &io::Error,
20) -> io::Result<()> {
21    let line = format!(
22        "{level} {} {}{CLOCK_ERROR_NOTE}{}]\n",
23        escape_controls(tag),
24        escape_controls(msg),
25        escape_controls(&error.to_string()),
26    );
27    io::stderr().lock().write_all(line.as_bytes())
28}
29
30fn escape_controls(text: &str) -> String {
31    let mut escaped = String::with_capacity(text.len());
32    for character in text.chars() {
33        if character.is_control() {
34            escaped.extend(character.escape_default());
35        } else {
36            escaped.push(character);
37        }
38    }
39    escaped
40}
41
42/// Format a [`LogRecord`] as a logcat-style console line.
43///
44/// Returns a String ending in `\n`.
45pub fn format_console(record: &LogRecord) -> String {
46    let (month, day, hour, min, sec, ms) = decompose_ts(record.ts);
47    let level_code = record.level.code();
48    // Truncate overly long tags; pad short ones.
49    let tag_display = if record.tag.len() > TAG_WIDTH {
50        format!("{}…", &record.tag[..TAG_WIDTH - 1])
51    } else {
52        format!("{: <width$}", record.tag, width = TAG_WIDTH)
53    };
54    format!(
55        "{:02}-{:02} {:02}:{:02}:{:02}.{:03}  {} {} {}\n",
56        month, day, hour, min, sec, ms, level_code, tag_display, record.msg
57    )
58}
59
60/// Write a [`LogRecord`] to stderr in console format.
61///
62/// Each call does a single `write_all`; the caller is responsible for
63/// not interleaving partial writes across threads (the global `log()`
64/// function synchronises via the file-sink mutex).
65pub fn write_console(record: &LogRecord) -> io::Result<()> {
66    let line = format_console(record);
67    let mut stderr = io::stderr().lock();
68    let use_color = stderr.is_terminal() && std::env::var_os("NO_COLOR").is_none();
69    let color = match record.level {
70        Level::Warn => Some("\x1b[33m"),
71        Level::Error => Some("\x1b[31m"),
72        _ => None,
73    };
74    if use_color && let Some(color) = color {
75        stderr.write_all(color.as_bytes())?;
76        stderr.write_all(line.as_bytes())?;
77        stderr.write_all(b"\x1b[0m")
78    } else {
79        stderr.write_all(line.as_bytes())
80    }
81}
82
83/// Decompose a nanosecond UNIX timestamp into local-time calendar fields
84/// and milliseconds.
85fn decompose_ts(ts_ns: u64) -> (u32, u32, u32, u32, u32, u32) {
86    // Convert ns → s + residual ns → ms
87    let secs = (ts_ns / 1_000_000_000) as i64;
88    let nanos_rem = (ts_ns % 1_000_000_000) as u32;
89    let ms = nanos_rem / 1_000_000;
90
91    // Use libc localtime_r for thread-safe local-time decomposition.
92    // Fall back to UTC if we can't determine local time.
93    #[cfg(unix)]
94    {
95        let local = localtime(secs);
96        let (year, month, day, hour, min, sec) = local;
97        // year is years since 1900; month is 0-11
98        let _ = year;
99        (month + 1, day, hour, min, sec, ms)
100    }
101    #[cfg(not(unix))]
102    {
103        // UTC fallback on non-Unix
104        let total_secs = secs;
105        let day_secs = total_secs % 86400;
106        let hour = (day_secs / 3600) as u32;
107        let min = ((day_secs % 3600) / 60) as u32;
108        let sec = (day_secs % 60) as u32;
109        let month = 1;
110        let day = 1;
111        (month, day, hour, min, sec, ms)
112    }
113}
114
115#[cfg(unix)]
116fn localtime(secs: i64) -> (i32, u32, u32, u32, u32, u32) {
117    use std::mem::MaybeUninit;
118    let ts = libc::time_t::try_from(secs).unwrap_or(0);
119    let mut tm: MaybeUninit<libc::tm> = MaybeUninit::uninit();
120    // SAFETY: localtime_r writes to the caller-provided tm; no aliasing.
121    let tm_ptr = unsafe {
122        libc::localtime_r(&ts, tm.as_mut_ptr());
123        tm.assume_init()
124    };
125    (
126        tm_ptr.tm_year,
127        tm_ptr.tm_mon as u32,
128        tm_ptr.tm_mday as u32,
129        tm_ptr.tm_hour as u32,
130        tm_ptr.tm_min as u32,
131        tm_ptr.tm_sec as u32,
132    )
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::Level;
139
140    #[test]
141    fn format_includes_level_code_and_tag() {
142        let rec = LogRecord {
143            ts: 0,
144            level: Level::Warn,
145            tag: "atlas".into(),
146            msg: "test message".into(),
147        };
148        let line = format_console(&rec);
149        assert!(line.contains(" W "), "expected W level code, got: {line}");
150        assert!(line.contains("atlas"), "expected tag, got: {line}");
151        assert!(line.contains("test message"), "expected msg, got: {line}");
152        assert!(line.ends_with('\n'), "should end with newline");
153    }
154
155    #[test]
156    fn tag_padded_to_fixed_width() {
157        let rec_short = LogRecord {
158            ts: 0,
159            level: Level::Info,
160            tag: "a".into(),
161            msg: "msg".into(),
162        };
163        let rec_long = LogRecord {
164            ts: 0,
165            level: Level::Info,
166            tag: "this_tag_is_way_too_long_for_display".into(),
167            msg: "msg".into(),
168        };
169        let short = format_console(&rec_short);
170        let long = format_console(&rec_long);
171        // Short tag padded to TAG_WIDTH
172        // Short tag padded to TAG_WIDTH: expect N spaces after "a"
173        let after_level: Vec<&str> = short.splitn(2, " I ").collect();
174        assert_eq!(after_level.len(), 2);
175        let rest = after_level[1]; // "a                        msg"
176        assert!(
177            rest.starts_with(&format!("{: <width$} ", "a", width = TAG_WIDTH)),
178            "tag 'a' should be padded to {TAG_WIDTH} chars, got rest: {rest:?}"
179        );
180        // Long tag should be truncated with …
181        assert!(
182            long.contains('…'),
183            "long tag should be truncated with '…', got: {long}"
184        );
185    }
186
187    #[test]
188    fn level_codes_in_output() {
189        for level in [Level::Debug, Level::Info, Level::Warn, Level::Error] {
190            let rec = LogRecord {
191                ts: 0,
192                level,
193                tag: "test".into(),
194                msg: String::new(),
195            };
196            let line = format_console(&rec);
197            let expected_code = format!(" {} ", level.code());
198            assert!(
199                line.contains(&expected_code),
200                "level {level:?}: expected '{expected_code}' in '{line}'"
201            );
202        }
203    }
204
205    #[test]
206    fn write_console_does_not_panic() {
207        let rec = LogRecord {
208            ts: 1765432100123456789,
209            level: Level::Info,
210            tag: "test".into(),
211            msg: "hello".into(),
212        };
213        // Just verify it doesn't panic; stderr is always writable.
214        write_console(&rec).unwrap();
215    }
216}
浙ICP备2023005800号-2 浙公网安备33010902005384号