Skip to main content

log/
lib.rs

1//! Xila's log subsystem.
2//!
3//! Code logs through the `log` crate's front end, re-exported here as
4//! [`error!`], [`warning!`], [`information!`], [`debug!`] and [`trace!`]; one
5//! [`LoggerTrait`] installed with [`initialize`] receives every message whose
6//! level its [`LoggerTrait::enabled`] accepts, including those of third-party
7//! crates that use `log` directly. The macros evaluate their arguments before
8//! that check, so keep expensive work out of messages that are often filtered
9//! out. Outside Core, use the re-export `xila::log`.
10//!
11//! # Levels
12//!
13//! [`Level`] has five levels, from the most to the least severe: `error`,
14//! `warning`, `information`, `debug` and `trace`. [`LevelFilter`] adds `off`
15//! and selects a level and every more severe one. Both print and parse as
16//! those lowercase names (parsing ignores ASCII case), for options such as
17//! `--log-level warning`.
18//!
19//! - `error`: an operation failed, and something the person or the system
20//!   expected did not happen.
21//! - `warning`: something unexpected happened, and the system recovered or
22//!   carried on in a degraded way.
23//! - `information`: rare, notable events, such as a subsystem starting. Not
24//!   per request, per packet or per click.
25//! - `debug`: details that help diagnose a problem.
26//! - `trace`: very frequent details, such as every call of a hot path.
27//!
28//! # Message style
29//!
30//! - Write in English. Messages are for developers and are not localised, so
31//!   never pass them through translation.
32//! - Use sentence case: start with a capital letter, and keep the rest
33//!   lowercase except names and acronyms (`Failed to mount the root file
34//!   system`).
35//! - Do not end a message with a period, an exclamation mark or a colon.
36//! - Do not start a message with `Xila:` or with the subsystem name (`UDP:`,
37//!   `WASI:`): the target, the module path by default, already says where it
38//!   comes from.
39//! - Show errors with their `Display` text (`{error}`), not with `{:?}`.
40//! - Put values after the text that names them (`Failed to open {path}:
41//!   {error}`), with no space before a colon.
42//! - Never log secrets or personal data: typed or pasted characters,
43//!   passwords, keys, random generator output, user names or full response
44//!   bodies. Log a count or a result instead.
45
46#![no_std]
47
48extern crate alloc;
49
50use alloc::fmt;
51use core::cmp::Ordering;
52use core::str::FromStr;
53use log_external::Log;
54use log_external::Metadata;
55pub use log_external::{debug, error, info as information, trace, warn as warning};
56use synchronization::once_lock::OnceLock;
57
58const BOLD: &str = "\x1b[0;1m";
59const RED: &str = "\x1b[0;41m";
60const YELLOW: &str = "\x1b[0;43m";
61const BLUE: &str = "\x1b[0;46m";
62const GREEN: &str = "\x1b[0;42m";
63const GREY: &str = "\x1b[0;100m";
64const RESET: &str = "\x1b[0m";
65
66/// The severity of a log message, from the most severe ([`Level::Error`]) to
67/// the least ([`Level::Trace`]).
68///
69/// Levels are ordered by verbosity, like the `log` crate's: `Error` is the
70/// smallest and `Trace` the largest.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
72#[repr(u8)]
73pub enum Level {
74    Error = 1,
75    Warning,
76    Information,
77    Debug,
78    Trace,
79}
80
81#[allow(non_upper_case_globals)]
82impl Level {
83    /// Former name of [`Level::Warning`], kept for one release.
84    ///
85    /// It works in expressions and patterns, but as an associated constant it
86    /// cannot be imported: `use log::Level::Warn` no longer compiles.
87    #[deprecated(note = "use `Level::Warning`")]
88    pub const Warn: Level = Level::Warning;
89
90    /// Former name of [`Level::Information`], kept for one release.
91    ///
92    /// It works in expressions and patterns, but as an associated constant it
93    /// cannot be imported: `use log::Level::Info` no longer compiles.
94    #[deprecated(note = "use `Level::Information`")]
95    pub const Info: Level = Level::Information;
96}
97
98impl Level {
99    /// Every level, from the most to the least severe.
100    pub const ALL: [Level; 5] = [
101        Level::Error,
102        Level::Warning,
103        Level::Information,
104        Level::Debug,
105        Level::Trace,
106    ];
107
108    /// The lowercase name of the level, as it prints and parses.
109    pub const fn as_str(self) -> &'static str {
110        match self {
111            Level::Error => "error",
112            Level::Warning => "warning",
113            Level::Information => "information",
114            Level::Debug => "debug",
115            Level::Trace => "trace",
116        }
117    }
118}
119
120impl fmt::Display for Level {
121    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
122        formatter.pad(self.as_str())
123    }
124}
125
126impl FromStr for Level {
127    type Err = ParseLevelError;
128
129    /// Parses a level name, ignoring ASCII case. Abbreviations such as `warn`
130    /// or `info` are refused.
131    fn from_str(name: &str) -> Result<Self, Self::Err> {
132        Level::ALL
133            .into_iter()
134            .find(|level| level.as_str().eq_ignore_ascii_case(name))
135            .ok_or(ParseLevelError(()))
136    }
137}
138
139/// The most verbose level that passes a filter, or [`LevelFilter::Off`] to let
140/// nothing pass.
141///
142/// A filter lets a level pass when the level is at most as verbose as the
143/// filter: [`LevelFilter::Warning`] lets errors and warnings pass.
144#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
145#[repr(u8)]
146pub enum LevelFilter {
147    Off = 0,
148    Error,
149    Warning,
150    Information,
151    Debug,
152    Trace,
153}
154
155impl LevelFilter {
156    /// Every filter, from [`LevelFilter::Off`] to the most verbose.
157    pub const ALL: [LevelFilter; 6] = [
158        LevelFilter::Off,
159        LevelFilter::Error,
160        LevelFilter::Warning,
161        LevelFilter::Information,
162        LevelFilter::Debug,
163        LevelFilter::Trace,
164    ];
165
166    /// The lowercase name of the filter, as it prints and parses.
167    pub const fn as_str(self) -> &'static str {
168        match self.level() {
169            Some(level) => level.as_str(),
170            None => "off",
171        }
172    }
173
174    /// The most verbose level that passes, or `None` for [`LevelFilter::Off`].
175    pub const fn level(self) -> Option<Level> {
176        match self {
177            LevelFilter::Off => None,
178            LevelFilter::Error => Some(Level::Error),
179            LevelFilter::Warning => Some(Level::Warning),
180            LevelFilter::Information => Some(Level::Information),
181            LevelFilter::Debug => Some(Level::Debug),
182            LevelFilter::Trace => Some(Level::Trace),
183        }
184    }
185
186    /// Whether messages of `level` pass this filter.
187    pub const fn enables(self, level: Level) -> bool {
188        level as u8 <= self as u8
189    }
190}
191
192impl From<Level> for LevelFilter {
193    fn from(level: Level) -> Self {
194        match level {
195            Level::Error => LevelFilter::Error,
196            Level::Warning => LevelFilter::Warning,
197            Level::Information => LevelFilter::Information,
198            Level::Debug => LevelFilter::Debug,
199            Level::Trace => LevelFilter::Trace,
200        }
201    }
202}
203
204impl fmt::Display for LevelFilter {
205    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
206        formatter.pad(self.as_str())
207    }
208}
209
210impl FromStr for LevelFilter {
211    type Err = ParseLevelError;
212
213    /// Parses `off` or a level name, ignoring ASCII case. Abbreviations such
214    /// as `warn` or `info` are refused.
215    fn from_str(name: &str) -> Result<Self, Self::Err> {
216        LevelFilter::ALL
217            .into_iter()
218            .find(|filter| filter.as_str().eq_ignore_ascii_case(name))
219            .ok_or(ParseLevelError(()))
220    }
221}
222
223impl PartialEq<LevelFilter> for Level {
224    fn eq(&self, other: &LevelFilter) -> bool {
225        *self as u8 == *other as u8
226    }
227}
228
229impl PartialOrd<LevelFilter> for Level {
230    fn partial_cmp(&self, other: &LevelFilter) -> Option<Ordering> {
231        Some((*self as u8).cmp(&(*other as u8)))
232    }
233}
234
235impl PartialEq<Level> for LevelFilter {
236    fn eq(&self, other: &Level) -> bool {
237        *self as u8 == *other as u8
238    }
239}
240
241impl PartialOrd<Level> for LevelFilter {
242    fn partial_cmp(&self, other: &Level) -> Option<Ordering> {
243        Some((*self as u8).cmp(&(*other as u8)))
244    }
245}
246
247/// The text given to [`Level::from_str`] or [`LevelFilter::from_str`] is not a
248/// level name.
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub struct ParseLevelError(());
251
252impl fmt::Display for ParseLevelError {
253    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
254        formatter.write_str("Unknown log level")
255    }
256}
257
258impl core::error::Error for ParseLevelError {}
259
260pub struct Record<'a> {
261    pub level: Level,
262    pub target: &'a str,
263    pub arguments: fmt::Arguments<'a>,
264}
265
266impl<'a> Record<'a> {
267    fn from_log_external(record: &log_external::Record<'a>) -> Self {
268        Self {
269            level: Level::from(record.level()),
270            target: record.target(),
271            arguments: *record.args(),
272        }
273    }
274}
275
276impl From<log_external::Level> for Level {
277    fn from(level: log_external::Level) -> Self {
278        match level {
279            log_external::Level::Error => Level::Error,
280            log_external::Level::Warn => Level::Warning,
281            log_external::Level::Info => Level::Information,
282            log_external::Level::Debug => Level::Debug,
283            log_external::Level::Trace => Level::Trace,
284        }
285    }
286}
287
288pub trait LoggerTrait: Send + Sync {
289    fn enabled(&self, level: Level) -> bool;
290
291    fn write(&self, arguments: fmt::Arguments);
292
293    fn log(&self, record: &Record) {
294        let (letter, color) = match record.level {
295            Level::Error => ("E", RED),
296            Level::Warning => ("W", YELLOW),
297            Level::Information => ("I", BLUE),
298            Level::Debug => ("D", GREEN),
299            Level::Trace => ("T", GREY),
300        };
301
302        self.write(format_args!(
303            "{} {} {} | {}{}{} | {}",
304            color, letter, RESET, BOLD, record.target, RESET, record.arguments
305        ))
306    }
307
308    fn flush(&self) {
309        // Implement flush logic if needed, e.g., flushing buffers to a file or console
310    }
311}
312
313struct Logger(&'static dyn LoggerTrait);
314
315impl Log for Logger {
316    fn enabled(&self, metadata: &Metadata) -> bool {
317        self.0.enabled(Level::from(metadata.level()))
318    }
319
320    fn log(&self, record: &log_external::Record) {
321        if !self.enabled(record.metadata()) {
322            return;
323        }
324        self.0.log(&Record::from_log_external(record));
325    }
326
327    fn flush(&self) {
328        self.0.flush();
329    }
330}
331
332static LOGGER_INSTANCE: OnceLock<Logger> = OnceLock::new();
333
334pub fn initialize(logger: &'static dyn LoggerTrait) -> Result<(), log_external::SetLoggerError> {
335    let log = LOGGER_INSTANCE.get_or_init(|| Logger(logger));
336
337    if install(log).is_err() {
338        logger.log(&Record {
339            level: Level::Error,
340            target: "log",
341            arguments: format_args!("Logger has already been initialized"),
342        });
343    }
344
345    Ok(())
346}
347
348/// Register `log` as the global logger and enable every level.
349#[cfg(target_has_atomic = "ptr")]
350fn install(log: &'static Logger) -> Result<(), log_external::SetLoggerError> {
351    let result = log_external::set_logger(log);
352    log_external::set_max_level(log_external::LevelFilter::Trace);
353    result
354}
355
356/// Register `log` as the global logger and enable every level.
357///
358/// Without pointer compare-and-swap, `log` only offers racy setters. One
359/// critical section serializes every call made through this crate.
360#[cfg(not(target_has_atomic = "ptr"))]
361fn install(log: &'static Logger) -> Result<(), log_external::SetLoggerError> {
362    critical_section::with(|_| {
363        // SAFETY: the critical section excludes every other `initialize`
364        // call, the only place Xila sets the logger and maximum level. Firmware
365        // and HAL crates must not call `log::set_logger_racy` or
366        // `log::set_max_level_racy` themselves outside this critical section.
367        // Logging concurrently with these setters is allowed by `log`.
368        unsafe {
369            let result = log_external::set_logger_racy(log);
370            log_external::set_max_level_racy(log_external::LevelFilter::Trace);
371            result
372        }
373    })
374}
375
376pub fn is_initialized() -> bool {
377    LOGGER_INSTANCE.try_get().is_some()
378}
379
380/// Copy the most recent complete log lines into the caller's buffer without
381/// blocking. Returns zero when no ring buffer is installed or a write is in
382/// progress.
383pub fn snapshot_tail(_output: &mut [u8]) -> usize {
384    // The log ring buffer is tracked in xila-project/core#840.
385    0
386}