Skip to main content

robonix_scribe/
lib.rs

1//! Scribe — Robonix unified logging facade.
2//!
3//! Single entry point: [`log()`].  Every component calls the same function;
4//! Scribe routes each record to stderr (human-readable) and to a per-tag
5//! JSON-lines file under `$SCRIBE_LOG_DIR` (or `./logs`).
6//!
7//! # Quick start
8//!
9//! ```rust,ignore
10//! robonix_scribe::init("executor");
11//! robonix_scribe::info!("robonix-executor starting");
12//! robonix_scribe::warn!("retry {}/{}", n, max);
13//! ```
14//!
15//! The `init()` call sets a process-wide default tag used by all subsequent
16//! [`info!`] / [`warn!`] / [`error!`] / [`debug!`] macro calls.  For
17//! per-message dynamic tags, use the lower-level [`log()`] function.
18
19use serde::{Deserialize, Deserializer, Serialize, Serializer};
20use std::fmt;
21use std::sync::OnceLock;
22
23pub mod format;
24pub mod sink;
25
26const CLOCK_ERROR_NOTE: &str = " [Chronos time read failed: ";
27
28/// Process-wide default tag, set once by [`init`].
29static DEFAULT_TAG: OnceLock<String> = OnceLock::new();
30
31/// Set the process-wide default tag.  Call once at startup, before any
32/// log call.  All [`info!`] / [`warn!`] / [`error!`] / [`debug!`] macros
33/// use this tag after it is set.
34///
35/// # Panics
36///
37/// Panics if called twice (intentional — one tag per process).
38pub fn init(tag: &str) {
39    DEFAULT_TAG
40        .set(tag.to_string())
41        .expect("robonix_scribe::init() called twice; set the tag once per process");
42}
43
44/// Initialise scribe with the process `tag` and apply the on-disk log level
45/// from a launch-config JSON — the system component's manifest config block
46/// that rbnx serialises and passes via `--config-json`. Reads the top-level
47/// `log` key (e.g. `{"log":"debug"}`); a valid level sets the file-sink floor
48/// for this process so the level actually reaches the log file (`rbnx logs`).
49///
50/// Use this instead of [`init`] in binaries launched with a config: the
51/// manifest's per-component `log:` had no effect before, because the level
52/// was parsed into a CLI flag the binary discarded. Absent / unparseable
53/// `log` falls back to the `SCRIBE_FILE_LEVEL` env / `Info` default.
54///
55/// Call once at startup, before the first log, on the main thread.
56pub fn init_from_config(tag: &str, config_json: Option<&str>) {
57    if let Some(level) = config_json
58        .and_then(|j| serde_json::from_str::<serde_json::Value>(j).ok())
59        .and_then(|v| v.get("log").and_then(|l| l.as_str()).and_then(parse_level))
60    {
61        let _ = FILE_LEVEL_OVERRIDE.set(level);
62    }
63    init(tag);
64}
65
66/// Return the process-wide default tag, or `"_default"` if `init()` has
67/// not been called yet.
68#[doc(hidden)]
69pub fn default_tag() -> &'static str {
70    DEFAULT_TAG.get().map(|s| s.as_str()).unwrap_or("_default")
71}
72
73/// Format a nanosecond UNIX timestamp as a local-time readable string:
74/// `"YYYY-MM-DD HH:MM:SS.nnnnnnnnn"`.
75///
76/// This is used for JSON serialisation of [`LogRecord::ts`].
77pub fn ts_fmt(ts_ns: u64) -> String {
78    let secs = (ts_ns / 1_000_000_000) as i64;
79    let nsec = (ts_ns % 1_000_000_000) as u32;
80    #[cfg(unix)]
81    let (year, month, day, hour, min, sec) = {
82        let ts = libc::time_t::try_from(secs).unwrap_or(0);
83        let mut tm: std::mem::MaybeUninit<libc::tm> = std::mem::MaybeUninit::uninit();
84        // SAFETY: localtime_r writes to caller-provided tm; no aliasing.
85        let tm_ptr = unsafe {
86            libc::localtime_r(&ts, tm.as_mut_ptr());
87            tm.assume_init()
88        };
89        (
90            tm_ptr.tm_year + 1900,
91            tm_ptr.tm_mon as u32 + 1,
92            tm_ptr.tm_mday as u32,
93            tm_ptr.tm_hour as u32,
94            tm_ptr.tm_min as u32,
95            tm_ptr.tm_sec as u32,
96        )
97    };
98    #[cfg(not(unix))]
99    let (year, month, day, hour, min, sec) = {
100        let day_secs = secs % 86400;
101        (
102            1970,
103            1u32,
104            1u32,
105            (day_secs / 3600) as u32,
106            ((day_secs % 3600) / 60) as u32,
107            (day_secs % 60) as u32,
108        )
109    };
110    format!("{year:04}-{month:02}-{day:02} {hour:02}:{min:02}:{sec:02}.{nsec:09}")
111}
112
113fn deserialize_ts<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
114    struct TsVisitor;
115    impl serde::de::Visitor<'_> for TsVisitor {
116        type Value = u64;
117        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
118            f.write_str("a nanosecond timestamp as string or integer")
119        }
120        fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<u64, E> {
121            Ok(v) // backward compat: accept raw integer
122        }
123        fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<u64, E> {
124            ts_parse(v).ok_or_else(|| E::custom(format!("invalid ts: {v}")))
125        }
126    }
127    d.deserialize_any(TsVisitor)
128}
129
130/// Parse a `ts_fmt`-style string back to nanosecond u64.  Returns `None`
131/// on malformed input.
132pub fn ts_parse(s: &str) -> Option<u64> {
133    // "YYYY-MM-DD HH:MM:SS.nnnnnnnnn" = 29 chars
134    if s.len() < 29 {
135        return None;
136    }
137    let year: i32 = s[0..4].parse().ok()?;
138    let month: u32 = s[5..7].parse().ok()?;
139    let day: u32 = s[8..10].parse().ok()?;
140    let hour: u32 = s[11..13].parse().ok()?;
141    let min: u32 = s[14..16].parse().ok()?;
142    let sec: u32 = s[17..19].parse().ok()?;
143    let nsec: u32 = s[20..29].parse().ok()?;
144    // Build a libc tm for mktime (Unix) or crude UTC calc.
145    #[cfg(unix)]
146    let secs = {
147        let mut tm: libc::tm = unsafe { std::mem::zeroed() };
148        tm.tm_year = year - 1900;
149        tm.tm_mon = month as i32 - 1;
150        tm.tm_mday = day as i32;
151        tm.tm_hour = hour as i32;
152        tm.tm_min = min as i32;
153        tm.tm_sec = sec as i32;
154        tm.tm_isdst = -1; // let libc figure out DST
155        let t = unsafe { libc::mktime(&mut tm) };
156        if t < 0 {
157            // mktime failed (e.g. date out of range for this TZ).
158            // Fall back: compute UTC epoch directly.
159            let days_before: [u32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
160            let y = year as u32;
161            let leap =
162                |y: u32| y.is_multiple_of(4) && !y.is_multiple_of(100) || y.is_multiple_of(400);
163            let days = (y - 1970) as u64 * 365 + ((y - 1969) / 4) as u64
164                - ((y - 1901) / 100) as u64
165                + ((y - 1601) / 400) as u64
166                + days_before[(month - 1) as usize] as u64
167                + if month > 2 && leap(y) { 1 } else { 0 }
168                + day as u64
169                - 1;
170            days * 86400 + hour as u64 * 3600 + min as u64 * 60 + sec as u64
171        } else {
172            t as u64
173        }
174    };
175    #[cfg(not(unix))]
176    let secs = {
177        let days_before_month: [u32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
178        let y = year as u32;
179        let leap = |y: u32| y.is_multiple_of(4) && !y.is_multiple_of(100) || y.is_multiple_of(400);
180        let days = (y - 1970) * 365 + ((y - 1969) / 4) - ((y - 1901) / 100)
181            + ((y - 1601) / 400)
182            + days_before_month[(month - 1) as usize]
183            + if month > 2 && leap(y) { 1 } else { 0 }
184            + day
185            - 1;
186        days as u64 * 86400 + hour as u64 * 3600 + min as u64 * 60 + sec as u64
187    };
188    let ts_ns = secs.checked_mul(1_000_000_000)?.checked_add(nsec as u64)?;
189    Some(ts_ns)
190}
191
192/// Severity level, ordered `Debug < Info < Warn < Error`.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
194#[serde(rename_all = "lowercase")]
195pub enum Level {
196    Debug,
197    Info,
198    Warn,
199    Error,
200}
201
202impl Level {
203    /// Single-character code used in console output.
204    pub fn code(self) -> &'static str {
205        match self {
206            Level::Debug => "D",
207            Level::Info => "I",
208            Level::Warn => "W",
209            Level::Error => "E",
210        }
211    }
212}
213
214impl fmt::Display for Level {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        f.write_str(self.code())
217    }
218}
219
220/// A single structured log record.
221///
222/// `ts` is nanoseconds since UNIX epoch internally; serialised as a
223/// human-readable `"YYYY-MM-DD HH:MM:SS.nnnnnnnnn"` string in JSON.
224#[derive(Debug, Clone, Deserialize)]
225pub struct LogRecord {
226    /// Nanosecond UNIX timestamp (internal u64; JSON: readable string).
227    #[serde(deserialize_with = "deserialize_ts")]
228    pub ts: u64,
229    /// Severity.
230    pub level: Level,
231    /// Source identifier — `provider_id` or component name.
232    pub tag: String,
233    /// Free-form log message body.
234    pub msg: String,
235}
236
237// Manual Serialize impl needed because we can't mix derive(Serialize) with
238// field-level serialize_with on a non-structural level in a derive.
239impl Serialize for LogRecord {
240    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
241        use serde::ser::SerializeStruct;
242        let mut st = s.serialize_struct("LogRecord", 4)?;
243        st.serialize_field("ts", &ts_fmt(self.ts))?;
244        st.serialize_field("level", &self.level)?;
245        st.serialize_field("tag", &self.tag)?;
246        st.serialize_field("msg", &self.msg)?;
247        st.end()
248    }
249}
250
251impl LogRecord {
252    /// Create a record from Chronos wall time, returning read/range errors.
253    /// Unverified readings are accepted; unavailable quality is noted in `msg`.
254    pub fn now(
255        level: Level,
256        tag: impl Into<String>,
257        msg: impl Into<String>,
258    ) -> std::io::Result<Self> {
259        let wall = robonix_chronos_clock::wall_time()?;
260        let ts = u64::try_from(wall.timestamp_ns).map_err(|_| {
261            std::io::Error::other(format!(
262                "Chronos wall timestamp {}ns does not fit u64",
263                wall.timestamp_ns
264            ))
265        })?;
266        let msg = msg.into();
267        let msg = if wall.available {
268            msg
269        } else {
270            format!("{msg} [Chronos wall clock unavailable: {}]", wall.reason)
271        };
272        Ok(Self {
273            ts,
274            level,
275            tag: tag.into(),
276            msg,
277        })
278    }
279}
280
281// ── Global lazy state ──────────────────────────────────────────────
282
283use std::sync::LazyLock;
284
285use crate::sink::FileSink;
286
287// ── Level filter thresholds / directory / sink ──────────────────────
288
289/// Resolved log directory — `$SCRIBE_LOG_DIR` or `"./logs"`.
290static LOG_DIR: LazyLock<std::path::PathBuf> = LazyLock::new(|| {
291    std::env::var("SCRIBE_LOG_DIR")
292        .map(std::path::PathBuf::from)
293        .unwrap_or_else(|_| std::path::PathBuf::from("./logs"))
294});
295
296/// Global file sink; `None` when the log directory can't be created
297/// (read-only filesystem, full disk, etc.).  When `None`, file writes
298/// are silently skipped — the process keeps running console-only.
299static FILE_SINK: LazyLock<Option<FileSink>> =
300    LazyLock::new(|| FileSink::new(LOG_DIR.as_path()).ok());
301
302// ── Level filter thresholds (read from env, lazy) ───────────────────
303
304/// Parse a level word (`debug`/`info`/`warn`/`warning`/`error`,
305/// case-insensitive). `None` for anything else.
306fn parse_level(s: &str) -> Option<Level> {
307    match s.to_lowercase().as_str() {
308        "debug" => Some(Level::Debug),
309        "info" => Some(Level::Info),
310        "warn" | "warning" => Some(Level::Warn),
311        "error" => Some(Level::Error),
312        _ => None,
313    }
314}
315
316/// Parse `SCRIBE_CONSOLE_LEVEL` / `SCRIBE_FILE_LEVEL` env var to a
317/// numeric floor.  Unrecognised values default to the given fallback.
318fn parse_level_env(key: &str, fallback: Level) -> Level {
319    std::env::var(key)
320        .ok()
321        .as_deref()
322        .and_then(parse_level)
323        .unwrap_or(fallback)
324}
325
326/// Per-process on-disk level override, set once by [`init_from_config`] from
327/// the launch config's `log` key. Takes precedence over `SCRIBE_FILE_LEVEL`
328/// when present, so a per-component `log:` in the deploy manifest actually
329/// controls that component's log file.
330static FILE_LEVEL_OVERRIDE: OnceLock<Level> = OnceLock::new();
331
332/// Minimum level for console (stderr) output.
333///
334/// Default: [`Level::Warn`]  — only Warn + Error reach the terminal.
335/// Set `SCRIBE_CONSOLE_LEVEL=info` to also see Info, or
336/// `SCRIBE_CONSOLE_LEVEL=debug` for everything.
337static CONSOLE_MIN: LazyLock<Level> =
338    LazyLock::new(|| parse_level_env("SCRIBE_CONSOLE_LEVEL", Level::Warn));
339
340/// Minimum level for per-tag log files.
341///
342/// Default: [`Level::Info`]  — Debug is suppressed on disk unless
343/// `SCRIBE_FILE_LEVEL=debug` is set.  Set `SCRIBE_FILE_LEVEL=error`
344/// to only persist errors.
345static FILE_MIN: LazyLock<Level> =
346    LazyLock::new(|| parse_level_env("SCRIBE_FILE_LEVEL", Level::Info));
347
348// ── Public API ─────────────────────────────────────────────────────
349
350/// Log a record with the given `level`, `tag`, and `msg`.
351///
352/// This is the **only** entry point for structured logging.  The first
353/// call transparently initialises the log directory and file sink.
354///
355/// # Per-sink level filtering
356///
357/// | Level  | Console (default) | File (default) |
358/// |--------|:-----:|:----:|
359/// | Debug  |  ✗    |  ✗   |
360/// | Info   |  ✗    |  ✓   |
361/// | Warn   |  ✓    |  ✓   |
362/// | Error  |  ✓    |  ✓   |
363///
364/// Override with `SCRIBE_CONSOLE_LEVEL` / `SCRIBE_FILE_LEVEL`.
365/// If time cannot be read or represented, write the original message and the
366/// error directly to stderr even for file-only levels, skipping the JSON sink.
367pub fn log(level: Level, tag: &str, msg: &str) {
368    // Only construct the timestamped record when at least one sink
369    // accepts this level — avoid wasted clock syscalls for Debug.
370    let console_ok = level >= *CONSOLE_MIN;
371    let file_min = FILE_LEVEL_OVERRIDE.get().copied().unwrap_or(*FILE_MIN);
372    let file_ok = level >= file_min;
373    if !console_ok && !file_ok {
374        return;
375    }
376    let record = match LogRecord::now(level, tag, msg) {
377        Ok(record) => record,
378        Err(error) => {
379            let _ = format::write_clock_error(level, tag, msg, &error);
380            return;
381        }
382    };
383    if console_ok {
384        let _ = format::write_console(&record);
385    }
386    if file_ok && let Some(sink) = FILE_SINK.as_ref() {
387        let _ = sink.write(&record);
388    }
389}
390
391/// Convenience: [`Level::Debug`].
392pub fn debug(tag: &str, msg: &str) {
393    log(Level::Debug, tag, msg);
394}
395
396/// Convenience: [`Level::Info`].
397pub fn info(tag: &str, msg: &str) {
398    log(Level::Info, tag, msg);
399}
400
401/// Convenience: [`Level::Warn`].
402pub fn warn(tag: &str, msg: &str) {
403    log(Level::Warn, tag, msg);
404}
405
406/// Convenience: [`Level::Error`].
407pub fn error(tag: &str, msg: &str) {
408    log(Level::Error, tag, msg);
409}
410
411/// Ingest a captured stdout/stderr line from a child process under `tag`.
412///
413/// A child that uses Scribe (Python `scribe_logger` in a docker container,
414/// or any binary that mirrors records to its console) emits lines already in
415/// console format — `MM-DD HH:MM:SS.mmm  L tag  msg`. Re-logging the whole
416/// line as a fresh record's `msg` double-stamps the timestamp/level/tag (it
417/// appears once in the JSON fields and again embedded in `msg`). When the line
418/// is recognised as Scribe console output, strip the prefix and re-emit just
419/// the inner message at its original level under `tag`; otherwise treat the
420/// line as opaque output and log it verbatim at Info. Unstamped clock-failure
421/// records retain their original level and diagnostic text.
422pub fn ingest(tag: &str, line: &str) {
423    match parse_console_line(line) {
424        Some((level, msg)) => log(level, tag, msg),
425        None => info(tag, line),
426    }
427}
428
429/// Recognise a Scribe console line and return its `(level, inner message)`.
430///
431/// Layout (see `format::format_console`): two-digit `MM-DD`, space, `HH:MM:SS`,
432/// `.mmm`, two spaces, a single level char `D/I/W/E`, space, the tag padded to
433/// 24 columns, space, then the message at byte 47. Validated by fixed ASCII
434/// positions so a non-Scribe line (e.g. raw ROS2 output) falls through to None.
435fn parse_console_line(line: &str) -> Option<(Level, &str)> {
436    let b = line.as_bytes();
437    let (code, message) =
438        if b.get(1) == Some(&b' ') && line.contains(CLOCK_ERROR_NOTE) && line.ends_with(']') {
439            (b[0], line)
440        } else {
441            // Shortest possible: 47-char prefix + at least one msg byte.
442            if b.len() < 48 {
443                return None;
444            }
445            if b[2] != b'-'
446                || b[5] != b' '
447                || b[8] != b':'
448                || b[11] != b':'
449                || b[14] != b'.'
450                || b[18] != b' '
451                || b[19] != b' '
452                || b[21] != b' '
453                || b[46] != b' '
454            {
455                return None;
456            }
457            for &i in &[0usize, 1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16, 17] {
458                if !b[i].is_ascii_digit() {
459                    return None;
460                }
461            }
462            (b[20], line.get(47..)?)
463        };
464    let level = match code {
465        b'D' => Level::Debug,
466        b'I' => Level::Info,
467        b'W' => Level::Warn,
468        b'E' => Level::Error,
469        _ => return None,
470    };
471    Some((level, message))
472}
473
474// ── Macros — process-wide default tag ───────────────────────────────
475
476/// Log at INFO level using the process-wide default tag set by [`init`].
477///
478/// ```rust,ignore
479/// robonix_scribe::init("executor");
480/// robonix_scribe::info!("connecting to atlas at {}", addr);
481/// ```
482#[macro_export]
483macro_rules! info {
484    ($($arg:tt)*) => {
485        $crate::log($crate::Level::Info, $crate::default_tag(), &format!($($arg)*))
486    };
487}
488
489/// Log at WARN level using the process-wide default tag set by [`init`].
490#[macro_export]
491macro_rules! warn {
492    ($($arg:tt)*) => {
493        $crate::log($crate::Level::Warn, $crate::default_tag(), &format!($($arg)*))
494    };
495}
496
497/// Log at ERROR level using the process-wide default tag set by [`init`].
498#[macro_export]
499macro_rules! error {
500    ($($arg:tt)*) => {
501        $crate::log($crate::Level::Error, $crate::default_tag(), &format!($($arg)*))
502    };
503}
504
505/// Log at DEBUG level using the process-wide default tag set by [`init`].
506#[macro_export]
507macro_rules! debug {
508    ($($arg:tt)*) => {
509        $crate::log($crate::Level::Debug, $crate::default_tag(), &format!($($arg)*))
510    };
511}
512
513// ── Tests ───────────────────────────────────────────────────────────
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518
519    #[test]
520    fn level_codes() {
521        assert_eq!(Level::Debug.code(), "D");
522        assert_eq!(Level::Info.code(), "I");
523        assert_eq!(Level::Warn.code(), "W");
524        assert_eq!(Level::Error.code(), "E");
525    }
526
527    #[test]
528    fn parse_console_round_trips_formatter() {
529        // A line produced by format_console must parse back to its level + msg,
530        // so re-ingesting a child's console echo strips the prefix (no
531        // double-stamped timestamp/tag).
532        for (level, msg) in [
533            (Level::Info, "[nav2] [smoother_server-2] launched."),
534            (Level::Warn, "rtabmap: republishing map"),
535            (Level::Error, "webui GET /api/map.png failed"),
536            (Level::Debug, "x"),
537        ] {
538            let rec = LogRecord::now(level, "nav2", msg).unwrap();
539            let line = format::format_console(&rec);
540            let line = line.trim_end_matches('\n');
541            assert_eq!(
542                parse_console_line(line),
543                Some((level, msg)),
544                "line={line:?}"
545            );
546        }
547    }
548
549    #[test]
550    fn parse_console_rejects_non_console_lines() {
551        // Raw child output (ROS2 logs, start-script prints) must fall through.
552        for raw in [
553            "[nav2/start] mode=docker (FORCE= PLATFORM=)",
554            "[INFO] [1782660318.498] [planner_server]: activating",
555            "",
556            "short",
557            "06-28 15:41:51.183 X nav2  bad level char",
558        ] {
559            assert_eq!(parse_console_line(raw), None, "raw={raw:?}");
560        }
561    }
562
563    #[test]
564    fn level_display_is_code() {
565        assert_eq!(Level::Info.to_string(), "I");
566    }
567
568    #[test]
569    fn level_ordering() {
570        assert!(Level::Debug < Level::Info);
571        assert!(Level::Info < Level::Warn);
572        assert!(Level::Warn < Level::Error);
573    }
574
575    #[test]
576    fn log_record_serialization_is_readable_string() {
577        let rec = LogRecord {
578            ts: 1765432100123456789,
579            level: Level::Info,
580            tag: "scene_svc".into(),
581            msg: "object registered".into(),
582        };
583        let json = serde_json::to_string(&rec).unwrap();
584        // ts is now a human-readable "YYYY-MM-DD HH:MM:SS.nnnnnnnnn" string.
585        assert!(
586            json.contains(r#""ts":""#),
587            "ts should be a JSON string, got: {json}"
588        );
589        assert!(json.contains(r#""level":"info""#));
590        assert!(json.contains(r#""tag":"scene_svc""#));
591        assert!(json.contains(r#""msg":"object registered""#));
592    }
593
594    #[test]
595    fn log_record_deserialization_readable_string() {
596        // New format: ts as readable string
597        let json = r#"{"ts":"2025-12-11 13:48:20.123456789","level":"info","tag":"scene_svc","msg":"object registered"}"#;
598        let rec: LogRecord = serde_json::from_str(json).unwrap();
599        assert_eq!(rec.level, Level::Info);
600        assert_eq!(rec.tag, "scene_svc");
601        assert_eq!(rec.msg, "object registered");
602        // The nanosecond value depends on local TZ → we just verify it's non-zero
603        assert!(rec.ts > 0, "parsed ts should be positive");
604    }
605
606    #[test]
607    fn log_record_deserialization_legacy_integer() {
608        // Legacy format: ts as raw integer (backward compat)
609        let json = r#"{"ts":1765432100123456789,"level":"info","tag":"scene_svc","msg":"object registered"}"#;
610        let rec: LogRecord = serde_json::from_str(json).unwrap();
611        assert_eq!(rec.ts, 1765432100123456789);
612        assert_eq!(rec.level, Level::Info);
613        assert_eq!(rec.tag, "scene_svc");
614        assert_eq!(rec.msg, "object registered");
615    }
616
617    #[test]
618    fn log_record_roundtrip() {
619        let rec = LogRecord {
620            ts: 1_700_000_000_000_000_000,
621            level: Level::Error,
622            tag: "test".into(),
623            msg: "roundtrip".into(),
624        };
625        let json = serde_json::to_string(&rec).unwrap();
626        let back: LogRecord = serde_json::from_str(&json).unwrap();
627        assert_eq!(back.level, rec.level);
628        assert_eq!(back.tag, rec.tag);
629        assert_eq!(back.msg, rec.msg);
630        // ts may differ slightly due to TZ roundtrip; verify within 1 day
631        let diff = back.ts.abs_diff(rec.ts);
632        assert!(
633            diff < 86_400_000_000_000,
634            "roundtrip ts diff too large: {diff} ns"
635        );
636    }
637
638    #[test]
639    fn log_record_now_has_reasonable_ts() {
640        let rec = LogRecord::now(Level::Debug, "test", "hello").unwrap();
641        // After 2020-01-01 in nanos
642        assert!(rec.ts > 1_577_836_800_000_000_000);
643        // Not in the far future
644        assert!(rec.ts < 4_000_000_000_000_000_000);
645    }
646
647    // ── log() integration tests ─────────────────────────────────
648    //
649    // NOTE: FILE_SINK is a LazyLock — it initialises once per process.
650    // These tests only verify the public API does not panic and that
651    // convenience wrappers route to the correct level.  File/directory
652    // behaviour is covered exhaustively by `sink::tests`.
653
654    #[test]
655    fn log_does_not_panic() {
656        log(Level::Debug, "smoke", "smoke test");
657        debug("smoke_d", "debug smoke");
658        info("smoke_i", "info smoke");
659        warn("smoke_w", "warn smoke");
660        error("smoke_e", "error smoke");
661    }
662
663    #[test]
664    fn convenience_wrappers_use_correct_levels() {
665        // Verify by inspecting a LogRecord produced by each wrapper.
666        let r_d = LogRecord::now(Level::Debug, "t", "d").unwrap();
667        let r_i = LogRecord::now(Level::Info, "t", "i").unwrap();
668        let r_w = LogRecord::now(Level::Warn, "t", "w").unwrap();
669        let r_e = LogRecord::now(Level::Error, "t", "e").unwrap();
670        assert_eq!(r_d.level, Level::Debug);
671        assert_eq!(r_i.level, Level::Info);
672        assert_eq!(r_w.level, Level::Warn);
673        assert_eq!(r_e.level, Level::Error);
674    }
675
676    #[test]
677    fn default_log_dir_is_dot_logs() {
678        let default = std::env::var("SCRIBE_LOG_DIR")
679            .map(std::path::PathBuf::from)
680            .unwrap_or_else(|_| std::path::PathBuf::from("./logs"));
681        assert_eq!(default, std::path::PathBuf::from("./logs"));
682    }
683
684    #[test]
685    fn default_tag_is_default_until_init() {
686        assert_eq!(default_tag(), "_default");
687    }
688
689    #[test]
690    fn macro_info_uses_default_tag() {
691        // This test parses the msg field to verify the tag used.
692        // We can't easily intercept the macro's output in unit tests,
693        // so we verify the default_tag() function works correctly.
694        // The actual macro routing is smoke-tested in integration.
695        assert_eq!(default_tag(), "_default");
696    }
697}
浙ICP备2023005800号-2 浙公网安备33010902005384号