nros_log/lib.rs
1//! Portable leveled-logging facade for nano-ros.
2//!
3//! ## Layering
4//!
5//! - This crate carries only the portable types + dispatcher +
6//! macros + `PlatformSink`. No backend code.
7//! - Per-platform log delivery is the responsibility of each
8//! `nros-platform-<rtos>` crate, exposing
9//! `nros_platform_log_write` / `nros_platform_log_flush` via the
10//! `nros_platform_*` ABI (header at
11//! `packages/platform/nros-platform-api/include/nros/platform.h`).
12//! - `PlatformSink` is the bridge: a single `LogSink` impl that
13//! forwards to the ABI. Apps that want fan-out (e.g.
14//! `Platform + /rosout`) compose a `&'static [&dyn LogSink]`
15//! manually and pass it to [`init`].
16//!
17//! ## Quick start
18//!
19//! ```ignore
20//! use nros_log::{Logger, Severity};
21//! use nros_log::{log_info, log_warn};
22//!
23//! static LOGGER: Logger = Logger::new("my_node");
24//!
25//! fn main() {
26//! nros_log::register_logger(&LOGGER);
27//! nros_log::init(nros_log::sinks::default());
28//! log_info!(&LOGGER, "started; domain = {}", 42);
29//! }
30//! ```
31
32// UNCONDITIONAL. This was `cfg_attr(not(feature = "std"), no_std)`, which
33// bought nothing: this crate's `std` feature is `std = ["alloc"]` over
34// `alloc = []`, so it enables no std functionality and the crate uses none.
35// The conditional form only meant that building with `std` compiled a
36// DIFFERENT crate -- a second configuration nobody wanted and no lane checked.
37//
38// ARCHITECTURE section 2 / phase-359: the terminal state of a core crate is
39// `core` or `core+alloc`. `check-core-crates-are-no-std` holds every core
40// crate to this spelling.
41#![no_std]
42#![deny(unsafe_op_in_unsafe_fn)]
43#![warn(missing_docs)]
44
45#[cfg(feature = "alloc")]
46extern crate alloc;
47
48// Phase 88.16.E — portable-atomic polyfill for CAS-less targets
49// (RISC-V `imc`, etc.). Feature unification: a consuming bare-metal
50// crate enables `unsafe-assume-single-core` / `critical-section` on
51// its own `portable-atomic` dep; native CAS targets get the
52// passthrough.
53use portable_atomic::{AtomicBool, AtomicPtr, AtomicU8, AtomicUsize, Ordering};
54
55pub mod early;
56#[cfg(feature = "log-compat")]
57pub mod log_compat;
58pub mod log_params;
59pub mod macros;
60pub mod pool;
61#[cfg(feature = "rosout")]
62pub mod rosout;
63pub mod sinks;
64pub mod throttle;
65
66mod buffer;
67
68/// The resolved `[knobs.log]` tenant, written by `build.rs` (phase-479 W5,
69/// issue 1037). One file, one place each value enters the crate.
70mod config {
71 include!(concat!(env!("OUT_DIR"), "/nros_log_config.rs"));
72
73 // `build.rs` range-checks the knob; this keeps a hand-edited or stale
74 // file from compiling into a ceiling above `off`.
75 #[allow(clippy::absurd_extreme_comparisons)]
76 const _: () = assert!(MAX_LEVEL <= 6, "NROS_LOG_MAX_LEVEL is 0..=6");
77}
78
79pub use buffer::{FormatBuffer, format_buffer_capacity};
80pub use log_params::{LogOccurrence, LogParams, ThrottleClock, ToLogParams};
81pub use pool::{
82 MAX_LOGGER_NAME_LEN, dynamic_logger_capacity, dynamic_logger_name_arena, dynamic_loggers_in_use,
83};
84pub use throttle::{ThrottleState, interval_ms_to_ns, throttle_decide};
85
86/// REP-2012 severity levels: rcutils's five, in rcutils's order, plus `Trace`.
87///
88/// NOT `rcutils_log_severity_t`'s numbering (`UNSET=0, DEBUG=10 ... FATAL=50`),
89/// and no `Unset` variant. The integer representation is stable and part of the
90/// ABI for `nros_platform_log_write`, so every value must be a level a sink can
91/// render; "no level of its own" is the verb [`Logger::unset_level`] instead.
92/// (The C surface's `rcl_log_severity_t` does carry rcutils's numbers and
93/// `UNSET`.) Lower value = more verbose.
94#[repr(u8)]
95#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
96pub enum Severity {
97 /// Per-instruction granularity. Off unless `max-level-trace` is
98 /// the active ceiling.
99 Trace = 0,
100 /// Diagnostic information useful while developing.
101 Debug = 1,
102 /// Normal operation events worth surfacing once.
103 Info = 2,
104 /// Unexpected but recoverable conditions.
105 Warn = 3,
106 /// Errors the caller should surface; the system continues.
107 Error = 4,
108 /// Unrecoverable — the system is about to abort.
109 Fatal = 5,
110}
111
112impl Severity {
113 /// Short uppercase label suitable for log-line rendering.
114 #[must_use]
115 pub const fn as_str(self) -> &'static str {
116 match self {
117 Self::Trace => "TRACE",
118 Self::Debug => "DEBUG",
119 Self::Info => "INFO",
120 Self::Warn => "WARN",
121 Self::Error => "ERROR",
122 Self::Fatal => "FATAL",
123 }
124 }
125
126 /// Stable `u8` discriminant for cross-ABI use.
127 #[must_use]
128 pub const fn as_u8(self) -> u8 {
129 self as u8
130 }
131
132 /// This severity on **rcutils's number line** — the one every ROS 2
133 /// artefact outside this crate uses.
134 ///
135 /// [`as_u8`](Self::as_u8) is this crate's own compact discriminant (`0..=5`,
136 /// chosen so a level comparison is an integer compare). It is NOT what a
137 /// `rcl_interfaces/msg/Log` carries, nor what `<rclc/log.h>`'s
138 /// `rcl_log_severity_t` crosses the FFI as, nor what
139 /// `rcutils_logging_set_logger_level` takes. Those are all rcutils's
140 /// `DEBUG=10 / INFO=20 / WARN=30 / ERROR=40 / FATAL=50`.
141 ///
142 /// THE ONE SPELLING of that mapping (one number with two derivations
143 /// agrees until the day it does not). `nros-c`'s
144 /// `rcl_log_severity_t::from_facade` is built on this, and a test there
145 /// pins the result against the values `<rclc/log.h>` declares — which is
146 /// the strongest join available, since this crate cannot see that header.
147 ///
148 /// `Trace` takes **5**, a value inside rcutils's own `UNSET`..`DEBUG` gap:
149 /// rcutils has no TRACE, and borrowing `DEBUG`'s number would make the two
150 /// levels indistinguishable on the wire.
151 #[must_use]
152 pub const fn rcutils_level(self) -> u8 {
153 match self {
154 Self::Trace => 5,
155 Self::Debug => 10,
156 Self::Info => 20,
157 Self::Warn => 30,
158 Self::Error => 40,
159 Self::Fatal => 50,
160 }
161 }
162}
163
164/// Reconstruct a [`Severity`] from its `u8` discriminant.
165///
166/// Returns `None` for `> 5`.
167#[must_use]
168pub const fn severity_from_u8(value: u8) -> Option<Severity> {
169 match value {
170 0 => Some(Severity::Trace),
171 1 => Some(Severity::Debug),
172 2 => Some(Severity::Info),
173 3 => Some(Severity::Warn),
174 4 => Some(Severity::Error),
175 5 => Some(Severity::Fatal),
176 _ => None,
177 }
178}
179
180/// Compile-time ceiling check used by the `nros_*!` macros.
181///
182/// Returns `true` iff `severity` is at or above the image's
183/// `NROS_LOG_MAX_LEVEL` (builtin `trace`, so everything). A
184/// `const fn` over a build-script constant, so a macro call below the ceiling
185/// folds to `if false { .. }` and its formatting is dead code — the elimination
186/// the old `max-level-*` features gave, without a feature.
187///
188/// The ceiling is a BOUND, not a threshold: [`Logger::set_level`] still moves
189/// each logger's runtime level, and a level below the ceiling is simply
190/// unreachable ([`Logger::is_enabled`] answers `false` there). rcutils keeps
191/// the same pair (`RCUTILS_LOG_MIN_SEVERITY_*` + `set_logger_level`).
192#[must_use]
193pub const fn severity_enabled_at_compile_time(severity: Severity) -> bool {
194 // `config::MAX_LEVEL` is 6 for `off`, above `Fatal` (5): nothing passes.
195 // The value is a build-script constant, and at its builtin (0 = trace) the
196 // comparison is always true — that is the point, not a slip.
197 #[allow(clippy::absurd_extreme_comparisons)]
198 let enabled = (severity as u8) >= config::MAX_LEVEL;
199 enabled
200}
201
202/// One log entry, handed to each [`LogSink`].
203///
204/// `message` is already formatted — sinks must NOT re-format.
205#[derive(Debug)]
206pub struct Record<'a> {
207 /// Severity of the record.
208 pub severity: Severity,
209 /// Name of the originating [`Logger`].
210 pub logger_name: &'a str,
211 /// Formatted message text (no trailing newline).
212 pub message: &'a str,
213 /// File the macro invocation came from (`core::file!()`).
214 pub file: &'static str,
215 /// Line within `file` (`core::line!()`).
216 pub line: u32,
217 /// Monotonic timestamp in nanoseconds. `0` if unavailable.
218 pub timestamp_ns: u64,
219}
220
221/// Backend a log record is delivered to.
222///
223/// Implementations must be `Sync` so the dispatcher can hold them
224/// in `&'static [&dyn LogSink]`. ISR-safety is per-impl.
225pub trait LogSink: Sync {
226 /// Render `record`. Called only when the record's severity passes
227 /// both the compile-time ceiling AND the [`Logger`]'s runtime
228 /// threshold.
229 fn log(&self, record: &Record<'_>);
230
231 /// Optional flush hook (default no-op).
232 fn flush(&self) {}
233
234 // Issue 2762.
235 /// Whether [`log`](Self::log) may run in several contexts at once:
236 /// threads, CPUs and interrupts.
237 ///
238 /// A re-entrant sink gets every record directly, in the context that
239 /// raised it, so concurrent loggers never queue behind one another for
240 /// it. A sink that is not (the default) is entered one record at a time
241 /// behind the process-wide dispatch guard, and a record that finds the
242 /// guard held waits in the hold queue for it, as before.
243 ///
244 /// Say `true` only when `log` is safe concurrently AND never logs
245 /// through `nros_log` itself. A re-entrant sink that does log is not
246 /// recursed into without bound: past [`REENTRANT_DEPTH`] nested or
247 /// concurrent deliveries, a record takes the guarded path for every sink.
248 /// Records from different contexts may reach a re-entrant sink
249 /// interleaved, in the order they were raised.
250 fn reentrant(&self) -> bool {
251 false
252 }
253}
254
255// Issue 2762.
256/// Deliveries to re-entrant sinks that may be in progress at once before a
257/// record takes the guarded path instead. It bounds a
258/// re-entrant sink that logs through `nros_log` (each nested record is one
259/// more), so it is kept small: a nested delivery is a frame on the raising
260/// stack. Concurrent loggers past it are not lost; they queue as they did
261/// before re-entrant sinks existed.
262pub const REENTRANT_DEPTH: usize = 8;
263
264/// Re-entrant deliveries in progress (issue 2762).
265static REENTRANT_ACTIVE: AtomicUsize = AtomicUsize::new(0);
266
267/// The stored byte meaning "this logger has NO level of its own", so its
268/// threshold is whatever [`Logger::default_level`] currently says.
269///
270/// phase-467 (ledger rows `c:log_severity_t` + `rust:Logger::set_default_level`).
271/// It cannot be `0`: that is `Severity::Trace`, the most verbose level, which
272/// is why storing rcutils's `UNSET` in a level byte used to select TRACE here
273/// where upstream restores a default. `u8::MAX` is outside the enum in the
274/// other direction, and being ABOVE `Fatal` is load-bearing in
275/// [`Logger::is_enabled`] — see the note there.
276const LEVEL_UNSET: u8 = u8::MAX;
277
278/// The threshold a logger with no level of its own resolves to.
279///
280/// ONE process-wide byte, which is the whole of our level hierarchy. rcutils
281/// resolves an unset logger by walking a DOTTED ANCESTRY (`x.y.z` → `x.y` →
282/// `x`) to `g_rcutils_logging_default_logger_level`; `nros_log` has no
283/// ancestry — [`get_logger`] is exact string equality over [`MAX_LOGGERS`]
284/// slots — so that walk degenerates here to exactly one step, and one step is
285/// what this is.
286///
287/// Deliberately not built further, and phase-467 recorded that as PERMANENT on
288/// ledger row `c:log_severity_t` rather than as work. A dotted name is accepted
289/// and is just a name with a dot in it; what is missing is the PARENT, and the
290/// two things that would give it one are both absent for the same reason.
291/// Upstream keys a level by NAME (`rcutils_logging_set_logger_level(const char
292/// *, int)` writes an allocator-backed severity map), so an ancestor there can
293/// carry a level without being a logger; here the level is an `AtomicU8` INSIDE
294/// the [`Logger`], so an ancestor would have to occupy one of the 32 slots to
295/// hold one. And the producer of dotted names upstream, `Logger::get_child`,
296/// has no allocator here to concatenate `parent.child` with. A resolver for a
297/// hierarchy nothing can construct is not a missing feature.
298///
299/// RFC-0102 reversed that and phase-479 built it: the premises went stale
300/// ([`get_or_create_logger`] copies runtime names into a static arena,
301/// `parent.child` fits a 48-byte stack buffer, and the ancestors a `get_child`
302/// produces are loggers already). The hierarchy is now a parent pointer on
303/// [`Logger`], linked at creation, and this byte is the LAST step of the walk
304/// rather than the only one.
305static DEFAULT_LEVEL: AtomicU8 = AtomicU8::new(Severity::Info as u8);
306
307/// A named logger with a runtime severity threshold.
308///
309/// A logger constructed with [`Logger::new`] has NO level of its own and
310/// follows [`Logger::default_level`] (itself [`Severity::Info`] until someone
311/// calls [`Logger::set_default_level`]). [`Logger::with_level`] and
312/// [`Logger::set_level`] give it one; [`Logger::unset_level`] takes it away
313/// again. Use [`register_logger`] to publish a `'static Logger` so multiple
314/// call sites with the same name share the same threshold.
315pub struct Logger {
316 name: &'static str,
317 /// Either a [`Severity`] discriminant or the private `LEVEL_UNSET`.
318 level: AtomicU8,
319 /// RFC-0102 D2 — the nearest EXISTING ancestor by dotted name (`a.b` for
320 /// `a.b.c`, else `a`), or null. A logger with no level of its own resolves
321 /// through this chain before falling to [`Logger::default_level`], which is
322 /// rcutils's effective-level rule. Set when a logger is published to the
323 /// intern table ([`register_logger`], [`get_or_create_logger`]), never on
324 /// the log path. Only ever points at a logger whose name is a STRICT
325 /// dotted prefix of this one's, so the chain is acyclic and shorter than
326 /// [`MAX_LOGGERS`].
327 parent: AtomicPtr<Logger>,
328 /// RFC-0102 D4 — set when a NODE's accessor resolves this logger
329 /// ([`resolve_node_logger`]). The `/rosout` sink publishes by it: upstream
330 /// rcl publishes only through a publisher correlated with a node's logger.
331 node: AtomicBool,
332}
333
334impl Logger {
335 /// `const`-construct with NO level of its own — the logger follows
336 /// [`Logger::default_level`], which is [`Severity::Info`] until something
337 /// moves it.
338 ///
339 /// This once stored `Severity::Info` outright until the process
340 /// default existed, and "the author wrote `new`" then looked exactly like
341 /// "the author wrote `with_level(.., Info)`". They are different
342 /// statements — one is a choice and the other is the absence of one — and
343 /// telling them apart is what lets [`Logger::set_default_level`] move the
344 /// first without overriding the second.
345 #[must_use]
346 pub const fn new(name: &'static str) -> Self {
347 Self {
348 name,
349 level: AtomicU8::new(LEVEL_UNSET),
350 parent: AtomicPtr::new(core::ptr::null_mut()),
351 node: AtomicBool::new(false),
352 }
353 }
354
355 /// `const`-construct with an explicit threshold.
356 #[must_use]
357 pub const fn with_level(name: &'static str, level: Severity) -> Self {
358 Self {
359 name,
360 level: AtomicU8::new(level as u8),
361 parent: AtomicPtr::new(core::ptr::null_mut()),
362 node: AtomicBool::new(false),
363 }
364 }
365
366 /// Logger name (used as `Record::logger_name`).
367 #[must_use]
368 pub const fn name(&self) -> &'static str {
369 self.name
370 }
371
372 /// The threshold this logger actually filters on — its own level if it has
373 /// one, otherwise its nearest ancestor's, otherwise
374 /// [`Logger::default_level`].
375 ///
376 /// This is `rcutils_logging_get_logger_effective_level`'s answer, not
377 /// `rcutils_logging_get_logger_level`'s: it is the number that decides
378 /// whether a record is emitted, which is the question a call site asks.
379 /// There is deliberately no accessor for "is a level set on this logger",
380 /// because nothing in the tree has a use for the difference and an
381 /// accessor per language is three more names for one fact.
382 #[must_use]
383 pub fn level(&self) -> Severity {
384 severity_from_u8(self.effective_level_byte()).unwrap_or(Severity::Info)
385 }
386
387 /// The nearest ancestor this logger resolves an unset level through, if
388 /// any. `None` for a root, and for every logger not yet
389 /// published to the intern table.
390 #[must_use]
391 pub fn parent(&self) -> Option<&'static Logger> {
392 let p = self.parent.load(Ordering::Acquire);
393 // SAFETY: `parent` is only ever stored from a `&'static Logger` (see
394 // `link_published`), and loggers are never freed.
395 if p.is_null() {
396 None
397 } else {
398 Some(unsafe { &*p })
399 }
400 }
401
402 /// Whether a node's accessor resolved this logger.
403 #[must_use]
404 pub fn is_node_logger(&self) -> bool {
405 self.node.load(Ordering::Relaxed)
406 }
407
408 /// Own level byte if set; else the first set level up the parent chain;
409 /// else the process default. The walk is bounded by [`MAX_LOGGERS`] even
410 /// though the chain is acyclic by construction, so a defect elsewhere can
411 /// cost a wrong answer but never a hang on the log path.
412 #[inline]
413 fn effective_level_byte(&self) -> u8 {
414 let own = self.level.load(Ordering::Relaxed);
415 if own != LEVEL_UNSET {
416 return own;
417 }
418 let mut p = self.parent.load(Ordering::Acquire);
419 let mut hops = 0;
420 while !p.is_null() && hops < MAX_LOGGERS {
421 // SAFETY: as in `parent()`.
422 let ancestor: &Logger = unsafe { &*p };
423 let level = ancestor.level.load(Ordering::Relaxed);
424 if level != LEVEL_UNSET {
425 return level;
426 }
427 p = ancestor.parent.load(Ordering::Acquire);
428 hops += 1;
429 }
430 DEFAULT_LEVEL.load(Ordering::Relaxed)
431 }
432
433 /// Give this logger a level of its own. It stops following
434 /// [`Logger::default_level`] until [`Logger::unset_level`].
435 pub fn set_level(&self, level: Severity) {
436 self.level.store(level as u8, Ordering::Relaxed);
437 }
438
439 /// Take this logger's own level away, so it follows
440 /// [`Logger::default_level`] again.
441 ///
442 /// `rcutils_logging_set_logger_level(name, RCUTILS_LOG_SEVERITY_UNSET)`'s
443 /// effect, and what `rclc_logger_set_level(logger, RCLC_LOG_SEVERITY_UNSET)`
444 /// reaches.
445 ///
446 /// rclrs spells this `logger.set_level(LogSeverity::Unset)`. Here it is a verb,
447 /// because [`Severity`] has no `Unset`: its values are the sink ABI.
448 pub fn unset_level(&self) {
449 self.level.store(LEVEL_UNSET, Ordering::Relaxed);
450 }
451
452 /// The threshold every logger with no level of its own filters on.
453 ///
454 /// [`Severity::Info`] until [`Logger::set_default_level`] moves it, which
455 /// is `RCUTILS_DEFAULT_LOGGER_DEFAULT_LEVEL`'s value and upstream's
456 /// starting point too.
457 #[must_use]
458 pub fn default_level() -> Severity {
459 severity_from_u8(DEFAULT_LEVEL.load(Ordering::Relaxed)).unwrap_or(Severity::Info)
460 }
461
462 /// Move the threshold that every logger WITHOUT a level of its own filters
463 /// on — `rclrs::Logger::set_default_level`.
464 ///
465 /// Takes effect immediately and retroactively: a `static LOGGER:
466 /// Logger = Logger::new("x")` that was compiled into the image long before
467 /// this call follows it, because "no level of its own" is a stored state
468 /// and not a value copied in at construction. That is the whole reason
469 /// this is a capability rather than a re-export of
470 /// `DEFAULT_LOGGER.set_level`, which moves the threshold of the ONE logger
471 /// named `"nros"` (ledger row `rust:Logger::set_default_level`).
472 ///
473 /// It does NOT override a logger that states its own level: after
474 /// `with_level(.., Warn)` or `set_level(Warn)`, `Warn` wins.
475 ///
476 /// Takes [`Severity`], not rclrs's `LogSeverity`: it has a `Trace` level rclrs
477 /// lacks and no `Unset`. Where rclrs passes `Unset` to restore the default
478 /// default, pass `Severity::Info`, which is what `Unset` restores upstream.
479 pub fn set_default_level(level: Severity) {
480 DEFAULT_LEVEL.store(level as u8, Ordering::Relaxed);
481 }
482
483 /// Whether a record at `severity` would be emitted by this
484 /// logger AT RUNTIME.
485 ///
486 /// THE HOT PATH of every log macro, on every target, so the shape here is
487 /// measured rather than chosen (the figures below are for the two-level
488 /// own-or-default form that preceded the ancestor walk). Resolving the
489 /// unset level SELECTS the byte to compare against and compares once,
490 /// instead of comparing twice and short-circuiting: measured at an inlined
491 /// call site with `rustc -O`, the select form is 13 instructions on
492 /// `thumbv7m-none-eabi` and **branch-free** (LLVM predicates the whole
493 /// fallback into one `ittt eq` block) against 16 with a branch for the
494 /// short-circuit form, and 10 against 12 on `x86_64`. The cost over the
495 /// single-load original (8 thumb / 4 x86_64 instructions) is one compare
496 /// against an immediate, plus a byte load of one process-global that a
497 /// logger with its own level never performs.
498 ///
499 /// `LEVEL_UNSET` being ABOVE `Fatal` rather than below `Trace` is what
500 /// keeps this correct if the select is ever reordered: `severity >=
501 /// u8::MAX` is false for every `Severity`, so an unresolved sentinel can
502 /// only ever suppress a record, never emit one at the most verbose level —
503 /// which is the failure `0` had.
504 ///
505 /// The ancestor walk changed the unset arm: it now walks the parent chain
506 /// before the process default. A logger WITH its own level still costs one
507 /// load and one compare; an unset root pays one extra pointer load; each
508 /// ancestor without a level of its own costs one more. No string work, on
509 /// any arm.
510 #[must_use]
511 ///
512 /// The image's compile-time CEILING (`NROS_LOG_MAX_LEVEL`) is
513 /// applied here too, first: a runtime level below it is unreachable. That
514 /// is what brings the C and C++ surfaces under the same bound — their
515 /// macros format on the C side and reach the facade through this check
516 /// (`rclc_log_emit_at`, `nros_log_is_enabled`), so the ceiling the Rust
517 /// macros fold away at compile time filters theirs at the FFI boundary.
518 pub fn is_enabled(&self, severity: Severity) -> bool {
519 severity_enabled_at_compile_time(severity)
520 && (severity as u8) >= self.effective_level_byte()
521 }
522
523 /// Whether a record at `severity` would be emitted, given both this
524 /// logger's runtime threshold AND a per-call-site throttle window.
525 ///
526 /// The order is load-bearing and is the same order
527 /// `rclcpp` uses: the SEVERITY test runs first, so a record the level
528 /// already filters does not consume the throttle window. Reversing them
529 /// makes a raised-then-lowered log level lose its first record for a whole
530 /// interval, which is the shape of bug nobody reports because it looks
531 /// like the throttle working.
532 ///
533 /// Consumes the window when it returns `true`, so call it exactly once per
534 /// candidate record — the `nros_*_throttle!` macros do.
535 ///
536 /// `now_ns` is the caller's monotonic clock; the macros pass
537 /// [`__timestamp_ns`]. Taking it as an argument rather than reading the
538 /// clock here is what lets the whole rule be tested without a platform
539 /// port, and is the same shape `rclcpp::RCLCPP_*_THROTTLE` uses when it
540 /// asks for a `Clock`.
541 #[must_use]
542 pub fn is_enabled_throttled(
543 &self,
544 severity: Severity,
545 state: &ThrottleState,
546 now_ns: u64,
547 interval_ns: u64,
548 ) -> bool {
549 self.is_enabled(severity) && state.should_log(now_ns, interval_ns)
550 }
551
552 /// Hand `record` to every registered sink, after the runtime
553 /// threshold check.
554 ///
555 /// Macros call this; user code should not.
556 pub fn dispatch(&self, record: &Record<'_>) {
557 if !self.is_enabled(record.severity) {
558 return;
559 }
560 dispatch_to_sinks(record);
561 }
562}
563
564// -----------------------------------------------------------------------------
565// Static intern table for `get_logger("name")`. Bounded; no alloc.
566// -----------------------------------------------------------------------------
567
568/// Maximum number of named loggers that can be registered via
569/// [`register_logger`]. Beyond this, [`get_logger`] returns
570/// [`DEFAULT_LOGGER`].
571pub const MAX_LOGGERS: usize = 32;
572
573/// Catch-all logger returned when the requested name is not
574/// registered (or the intern table is full).
575pub static DEFAULT_LOGGER: Logger = Logger::new("nros");
576
577mod intern {
578 use super::{AtomicPtr, Logger, MAX_LOGGERS, Ordering};
579
580 pub(super) struct InternTable {
581 slots: [AtomicPtr<Logger>; MAX_LOGGERS],
582 }
583
584 impl InternTable {
585 /// Every published logger, in slot order.
586 pub(super) fn iter(&self) -> impl Iterator<Item = &'static Logger> + '_ {
587 self.slots.iter().map_while(|slot| {
588 let ptr = slot.load(Ordering::Acquire);
589 // SAFETY: same publication invariant as `lookup`.
590 if ptr.is_null() {
591 None
592 } else {
593 Some(unsafe { &*ptr })
594 }
595 })
596 }
597
598 pub(super) const fn new() -> Self {
599 // `AtomicPtr::new` is `const` on both `core::sync::atomic`
600 // and `portable_atomic`, so we can initialise the array
601 // by repeating the call rather than naming a `const` —
602 // which clippy flags as interior-mutable.
603 #[allow(clippy::declare_interior_mutable_const)]
604 const NULL: AtomicPtr<Logger> = AtomicPtr::new(core::ptr::null_mut());
605 Self {
606 slots: [NULL; MAX_LOGGERS],
607 }
608 }
609
610 pub(super) fn lookup(&self, name: &str) -> Option<&'static Logger> {
611 for slot in &self.slots {
612 let ptr = slot.load(Ordering::Acquire);
613 if ptr.is_null() {
614 return None;
615 }
616 // SAFETY: pointer published via Release after the
617 // owner constructed a `'static Logger`. The Acquire
618 // load synchronizes.
619 let logger: &'static Logger = unsafe { &*ptr };
620 if logger.name() == name {
621 return Some(logger);
622 }
623 }
624 None
625 }
626
627 pub(super) fn insert(&self, logger: &'static Logger) -> Option<&'static Logger> {
628 if let Some(existing) = self.lookup(logger.name()) {
629 return Some(existing);
630 }
631 let ptr = logger as *const _ as *mut Logger;
632 for slot in &self.slots {
633 if slot
634 .compare_exchange(
635 core::ptr::null_mut(),
636 ptr,
637 Ordering::AcqRel,
638 Ordering::Acquire,
639 )
640 .is_ok()
641 {
642 return Some(logger);
643 }
644 let existing_ptr = slot.load(Ordering::Acquire);
645 if !existing_ptr.is_null() {
646 // SAFETY: same publication invariant as `lookup`.
647 let existing: &'static Logger = unsafe { &*existing_ptr };
648 if existing.name() == logger.name() {
649 return Some(existing);
650 }
651 }
652 }
653 None
654 }
655 }
656}
657
658static INTERN: intern::InternTable = intern::InternTable::new();
659
660/// The dotted ancestors of `name`, nearest first: `a.b.c` yields `a.b`, `a`.
661fn dotted_ancestors(name: &str) -> impl Iterator<Item = &str> {
662 let mut rest = name;
663 core::iter::from_fn(move || {
664 let cut = rest.rfind('.')?;
665 rest = &rest[..cut];
666 Some(rest)
667 })
668}
669
670/// RFC-0102 D2 — wire a logger that was JUST published into the hierarchy.
671///
672/// 1. Its parent is its nearest EXISTING dotted ancestor.
673/// 2. Every published logger whose current parent is a FARTHER ancestor than
674/// `new` (or which has none) and whose name has `new`'s as a dotted prefix
675/// is re-pointed at `new`. So the result does not depend on creation order:
676/// `a.b.c` created before `a.b` still resolves through `a.b` once it exists.
677///
678/// Runs on publication only — one pass over at most [`MAX_LOGGERS`] slots.
679/// Creation is expected at initialisation; two loggers created at the same
680/// instant from different threads can leave a link one level FARTHER than
681/// ideal, never one pointing at a non-ancestor, because every store here is of
682/// a logger whose name is a strict dotted prefix of the target's.
683fn link_published(new: &'static Logger) {
684 let ptr = new as *const Logger as *mut Logger;
685 if let Some(parent) = dotted_ancestors(new.name()).find_map(|a| INTERN.lookup(a)) {
686 new.parent
687 .store(parent as *const Logger as *mut Logger, Ordering::Release);
688 }
689 let n = new.name();
690 for other in INTERN.iter() {
691 let on = other.name();
692 let is_descendant =
693 on.len() > n.len() && on.starts_with(n) && on.as_bytes()[n.len()] == b'.';
694 if !is_descendant {
695 continue;
696 }
697 let closer = match other.parent() {
698 None => true,
699 Some(current) => current.name().len() < n.len(),
700 };
701 if closer {
702 other.parent.store(ptr, Ordering::Release);
703 }
704 }
705}
706
707/// Publish through the intern table and, when THIS call did the inserting,
708/// link the logger into the hierarchy. The one spelling both publication
709/// paths use.
710fn publish(logger: &'static Logger) -> Option<&'static Logger> {
711 let published = INTERN.insert(logger)?;
712 if core::ptr::eq(published, logger) {
713 link_published(published);
714 }
715 Some(published)
716}
717
718/// Publish `logger` under its name so subsequent `get_logger`
719/// calls with that name return THIS reference.
720///
721/// On name collision returns the pre-existing entry (the input
722/// `logger` is NOT inserted). On a full table returns
723/// [`DEFAULT_LOGGER`].
724pub fn register_logger(logger: &'static Logger) -> &'static Logger {
725 publish(logger).unwrap_or(&DEFAULT_LOGGER)
726}
727
728/// Look up a registered logger by name. Returns [`DEFAULT_LOGGER`]
729/// if none is registered (call [`register_logger`] for a `'static
730/// Logger` to publish one).
731///
732/// Total — every call returns a usable handle the macros can
733/// dispatch through.
734#[must_use]
735pub fn get_logger(name: &str) -> &'static Logger {
736 INTERN.lookup(name).unwrap_or(&DEFAULT_LOGGER)
737}
738
739/// Look up a logger by name, CREATING one if the name is new.
740///
741/// This is the shape `rclcpp::get_logger` / `rcutils`' logger
742/// lookup have, and the one a wrapper needs: [`get_logger`] answers
743/// [`DEFAULT_LOGGER`] for an unregistered name, so a C or C++ caller doing
744/// `set_level(get_logger("nav"), Debug)` over the lookup-only form would have
745/// moved the threshold of the catch-all logger that EVERY other unregistered
746/// name also resolves to. Same call, same types, different effect.
747///
748/// Storage is the bounded static arena in [`pool`], sized by the
749/// `NROS_LOG_DYNAMIC_LOGGERS` knob (env > board > 16). Returns `None` — never a
750/// logger under the wrong name — when:
751///
752/// * `name` is empty or longer than [`MAX_LOGGER_NAME_LEN`],
753/// * the name arena or the logger arena is full,
754/// * the [`MAX_LOGGERS`] intern table is full.
755///
756/// Callers decide what an exhausted arena means for them; `nros-c` reports it
757/// and falls back to [`DEFAULT_LOGGER`] loudly rather than silently.
758///
759/// Loggers created this way are never destroyed — the arena has no free list,
760/// which is what makes the returned `&'static Logger` honest on `no_std`.
761#[must_use]
762pub fn get_or_create_logger(name: &str) -> Option<&'static Logger> {
763 if let Some(existing) = INTERN.lookup(name) {
764 return Some(existing);
765 }
766 let interned = pool::intern_name(name)?;
767 let placed = pool::place(Logger::new(interned))?;
768 // Not `register_logger`: that answers `DEFAULT_LOGGER` on a full table,
769 // which would hand back a logger under the wrong name — the exact aliasing
770 // this function exists to avoid. On a lost race `insert` returns the
771 // winner and our slot is spent, which `pool::dynamic_loggers_in_use`
772 // reports.
773 publish(placed)
774}
775
776/// Why [`Logger::create_child`] made no child.
777///
778/// rclrs's `create_child` is fallible too (`Result<Logger, RclrsError>`), so a
779/// Rust caller chooses its own fallback (`parent.create_child("x").unwrap_or(parent)`).
780/// The C and C++ surfaces, whose upstream shapes cannot report failure, fall
781/// back to the parent automatically.
782#[derive(Debug, Clone, Copy, PartialEq, Eq)]
783pub enum ChildError {
784 /// The child's full name is longer than [`MAX_LOGGER_NAME_LEN`] bytes.
785 NameTooLong {
786 /// Bytes the full name would have.
787 len: usize,
788 /// [`MAX_LOGGER_NAME_LEN`].
789 max: usize,
790 },
791 /// The full name would be empty: an empty `child_name` under the
792 /// catch-all, whose children are top-level names.
793 EmptyName,
794 /// The runtime-logger arena, its name bytes, or the intern table is full.
795 ArenaFull,
796}
797
798impl core::fmt::Display for ChildError {
799 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
800 match self {
801 Self::NameTooLong { len, max } => {
802 write!(
803 f,
804 "child logger name is {len} bytes, over the {max}-byte limit"
805 )
806 }
807 Self::EmptyName => f.write_str("child logger name is empty"),
808 Self::ArenaFull => f.write_str(
809 "no runtime logger slot left (arena, name bytes, or intern table is full)",
810 ),
811 }
812 }
813}
814
815impl Logger {
816 /// A logger that is a descendant of this one — rclrs's `create_child`,
817 /// rclcpp's `get_child`.
818 ///
819 /// Named `"{self}.{child_name}"`, except that the catch-all
820 /// ([`DEFAULT_LOGGER`]) has top-level children: its child is named
821 /// `child_name`, as rclrs does for its empty-named default logger.
822 ///
823 /// A child with no level of its own filters at its nearest ancestor's
824 /// (rcutils's rule), so `parent.set_level(Debug)` reaches it.
825 /// Idempotent: the same name returns the same logger, so a call inside a
826 /// log statement costs one intern-table lookup.
827 ///
828 /// Takes `&'static self` because the child links to its parent by
829 /// reference. `self` is published to the intern table first if it was
830 /// not, so a `static` parent nobody registered still passes its level on.
831 ///
832 /// # Errors
833 /// [`ChildError`] when the full name is over [`MAX_LOGGER_NAME_LEN`] or
834 /// empty, or no slot is left. The name is built in a stack buffer; nothing
835 /// is allocated.
836 pub fn create_child(
837 &'static self,
838 child_name: impl core::borrow::Borrow<str>,
839 ) -> Result<&'static Logger, ChildError> {
840 let child = child_name.borrow();
841 let top = core::ptr::eq(self, &DEFAULT_LOGGER);
842 let len = if top {
843 child.len()
844 } else {
845 self.name.len() + 1 + child.len()
846 };
847 if len == 0 {
848 return Err(ChildError::EmptyName);
849 }
850 if len > MAX_LOGGER_NAME_LEN {
851 return Err(ChildError::NameTooLong {
852 len,
853 max: MAX_LOGGER_NAME_LEN,
854 });
855 }
856 if !top && INTERN.lookup(self.name).is_none() {
857 // A full table leaves the child unlinked: it then filters at the
858 // process default, which is what an unregistered parent meant
859 // before RFC-0102 too.
860 let _ = publish(self);
861 }
862 let mut buf = [0u8; MAX_LOGGER_NAME_LEN];
863 let mut at = 0;
864 if !top {
865 buf[..self.name.len()].copy_from_slice(self.name.as_bytes());
866 at = self.name.len();
867 buf[at] = b'.';
868 at += 1;
869 }
870 buf[at..len].copy_from_slice(child.as_bytes());
871 // SAFETY: two `&str`s joined by an ASCII `.` are valid UTF-8, and the
872 // cut is at their end.
873 let name = unsafe { core::str::from_utf8_unchecked(&buf[..len]) };
874 get_or_create_logger(name).ok_or(ChildError::ArenaFull)
875 }
876}
877
878/// The published logger called `name`, if any — the lookup the `/rosout`
879/// sink filters by (RFC-0102 D4), which sees a record's name, not its logger.
880#[cfg(feature = "rosout")]
881pub(crate) fn find_published(name: &str) -> Option<&'static Logger> {
882 INTERN.lookup(name)
883}
884
885/// [`resolve_logger`] for a NODE's own logger, marking it as one — the one
886/// spelling the node-shaped accessors use (`Node::logger`,
887/// `rclc_node_get_logger`, the C++ node's), so the `/rosout` sink can publish
888/// what upstream publishes. The catch-all is never marked: a node
889/// whose name fell back to it would otherwise publish every unnamed logger.
890#[must_use]
891pub fn resolve_node_logger(name: &str) -> &'static Logger {
892 let logger = resolve_logger(name);
893 if !core::ptr::eq(logger, &DEFAULT_LOGGER) {
894 logger.node.store(true, Ordering::Relaxed);
895 }
896 logger
897}
898
899/// Resolve `name` to a logger — the TOTAL form of [`get_or_create_logger`],
900/// and the one spelling every node-shaped accessor uses.
901///
902/// Four accessors answer "which logger is this node's?" —
903/// `nros_node::executor::Node::logger`, `rclc_node_get_logger`,
904/// `nros_cpp_node_get_logger` and `rclc_log_get_logger`. All four had the same
905/// job and, before this, three of them called [`get_logger`], which is a
906/// LOOKUP: a node whose name nobody `register_logger`ed resolved to
907/// [`DEFAULT_LOGGER`]. Two nodes in one image therefore emitted every record
908/// under the same name, `"nros"` — the sentinel W5 replaced, arrived at by a
909/// different route.
910///
911/// This creates instead, and falls back to [`DEFAULT_LOGGER`] only when it
912/// cannot — an empty or over-long name, or an exhausted arena — and says so at
913/// WARN when it does, because the catch-all's threshold is SHARED and a silent
914/// alias makes `set_level` on the result move every other unnamed logger's bar
915/// with it. The report is ONE per process: a C++ `NROS_LOG_*` call site asks
916/// `node.get_logger()` on every line, so a per-call report would be a flood.
917///
918/// Lookup comes first, so an image that pre-registered a `'static Logger` under
919/// the node's name still gets that exact reference and its threshold.
920#[must_use]
921pub fn resolve_logger(name: &str) -> &'static Logger {
922 if let Some(logger) = get_or_create_logger(name) {
923 return logger;
924 }
925 // ONE report per process. This is reached from `Node::get_logger()`, which
926 // a C++ call site invokes inside every `NROS_LOG_*` macro — so a node whose
927 // name is longer than `MAX_LOGGER_NAME_LEN` (node names may be 64 bytes,
928 // logger names 48) would otherwise emit a warning per log line, and the
929 // diagnostic would be the flood. The first failure is the informative one:
930 // the arena only ever gets fuller.
931 static REPORTED: AtomicU8 = AtomicU8::new(0);
932 if REPORTED.swap(1, Ordering::Relaxed) != 0 {
933 return &DEFAULT_LOGGER;
934 }
935 let (used, total) = dynamic_logger_name_arena();
936 crate::log_warn!(
937 &DEFAULT_LOGGER,
938 "resolve_logger(\"{name}\"): no logger created — {} of {} slots and {used} of {total} \
939 name bytes are spent, or the name is over {} bytes. Returning the catch-all logger, \
940 whose threshold is SHARED: raise NROS_LOG_DYNAMIC_LOGGERS rather than calling \
941 set_level on this handle. Reported once per process.",
942 dynamic_loggers_in_use(),
943 dynamic_logger_capacity(),
944 MAX_LOGGER_NAME_LEN,
945 );
946 &DEFAULT_LOGGER
947}
948
949// -----------------------------------------------------------------------------
950// Sink list. Set once at `init`; read every dispatch.
951// -----------------------------------------------------------------------------
952
953static SINKS_PTR: AtomicPtr<&'static [&'static dyn LogSink]> =
954 AtomicPtr::new(core::ptr::null_mut());
955
956// issue 0710 — `init_default()` was here. It named a default this crate can no
957// longer name: the platform sink moved to `nros_platform_cffi::log`, where the
958// ABI it speaks is a dependency rather than a feature. Call
959// `nros_platform_cffi::log::init_default()`, or `init()` with your own sinks.
960
961/// Install the global sink list.
962///
963/// MUST be called at app startup BEFORE any record-emitting macro
964/// runs (otherwise the dispatch is a no-op — records are silently
965/// dropped). Calling `init` more than once swaps the list
966/// atomically; the previous pointer is leaked (intentional: the
967/// read path is lock-free so we can't safely free).
968///
969/// The sinks themselves must outlive the program (`'static`).
970pub fn init(sinks: &'static [&'static dyn LogSink]) {
971 // Indirect through a small `'static` cell so the read path
972 // dereferences a fat-pointer-sized slot rather than reading
973 // a wide pointer atomically.
974 #[cfg(feature = "alloc")]
975 {
976 let boxed: alloc::boxed::Box<&'static [&'static dyn LogSink]> =
977 alloc::boxed::Box::new(sinks);
978 let ptr = alloc::boxed::Box::into_raw(boxed);
979 SINKS_PTR.store(ptr, Ordering::Release);
980 }
981 #[cfg(not(feature = "alloc"))]
982 {
983 static CELL: SinkSlot = SinkSlot::new();
984 CELL.store(sinks);
985 SINKS_PTR.store(CELL.as_ptr(), Ordering::Release);
986 }
987 // AFTER publishing, so a record raised during the drain reaches `sinks`
988 // directly rather than joining a ring nobody will drain again. Overflow is
989 // reported by the same path (`report_lost`).
990 deliver_held();
991}
992
993#[cfg(not(feature = "alloc"))]
994struct SinkSlot {
995 inner: core::cell::UnsafeCell<Option<&'static [&'static dyn LogSink]>>,
996}
997
998#[cfg(not(feature = "alloc"))]
999// SAFETY: only written from `init`, which the user contracts to call
1000// once at startup before any concurrent reader exists.
1001unsafe impl Sync for SinkSlot {}
1002
1003#[cfg(not(feature = "alloc"))]
1004impl SinkSlot {
1005 const fn new() -> Self {
1006 Self {
1007 inner: core::cell::UnsafeCell::new(None),
1008 }
1009 }
1010 fn store(&self, sinks: &'static [&'static dyn LogSink]) {
1011 // SAFETY: see Sync note above.
1012 unsafe {
1013 *self.inner.get() = Some(sinks);
1014 }
1015 }
1016 fn as_ptr(&self) -> *mut &'static [&'static dyn LogSink] {
1017 self.inner.get().cast()
1018 }
1019}
1020
1021// -----------------------------------------------------------------------------
1022// Appendable sink registry (phase-417 W4.d).
1023//
1024// `init` REPLACES the list, which is right for the board — it names, once, the
1025// whole delivery it chose. It is the wrong verb for a consumer: C and C++ had
1026// no way to install a sink at all (`rclc_log_init(void)` takes no arguments
1027// and hardcodes the platform default), and a library that wants to tee records
1028// to /rosout cannot call `init` without discarding whatever the board
1029// installed.
1030//
1031// So `add_sink` APPENDS, and dispatch walks both lists. The two are kept
1032// separate rather than merged into one growable list because they have
1033// different owners and different lifetimes-of-decision: `init` may be called
1034// again and swap the board's choice wholesale, and doing so must not silently
1035// unregister a consumer's sink.
1036// -----------------------------------------------------------------------------
1037
1038/// How many sinks [`add_sink`] can append on top of the [`init`] list.
1039///
1040/// Small on purpose: the appendable list is for consumers that TEE (a /rosout
1041/// bridge, a test collector), not for composing a delivery — a board composing
1042/// its own delivery passes the whole slice to [`init`].
1043pub const MAX_ADDED_SINKS: usize = 4;
1044
1045struct AddedSinks {
1046 slots: core::cell::UnsafeCell<[Option<&'static dyn LogSink>; MAX_ADDED_SINKS]>,
1047 /// Number of slots fully written. `Release` on publish, `Acquire` on read.
1048 len: AtomicUsize,
1049}
1050
1051// SAFETY: writes happen only under `ADD_LOCK` and only to the slot at index
1052// `len`, which no reader looks at until the `Release` store to `len` that
1053// follows the write is observed by an `Acquire` load. A slot is written once
1054// and never rewritten.
1055unsafe impl Sync for AddedSinks {}
1056
1057static ADDED: AddedSinks = AddedSinks {
1058 slots: core::cell::UnsafeCell::new([None; MAX_ADDED_SINKS]),
1059 len: AtomicUsize::new(0),
1060};
1061
1062/// Serialises `add_sink` against itself.
1063///
1064/// A spin lock, held for two stores with no call inside it, is admissible here
1065/// where the in-order-publish alternative is not: that one has a thread
1066/// waiting on ANOTHER thread's progress, which on a single-core RTOS with
1067/// priorities is a deadlock rather than a delay. Do not call `add_sink` from
1068/// an ISR.
1069static ADD_LOCK: AtomicBool = AtomicBool::new(false);
1070
1071/// Append `sink` to the sinks every record is delivered to.
1072///
1073/// Returns `false` when [`MAX_ADDED_SINKS`] are already registered — the sink
1074/// is NOT installed, and the caller is expected to say so rather than carry on
1075/// as if it were.
1076///
1077/// Records raised before any sink existed are replayed into `sink` here, the
1078/// same way [`init`] replays them, so the first sink to arrive still sees the
1079/// boot story regardless of which of the two calls installed it.
1080pub fn add_sink(sink: &'static dyn LogSink) -> bool {
1081 while ADD_LOCK
1082 .compare_exchange(false, true, Ordering::Acquire, Ordering::Acquire)
1083 .is_err()
1084 {
1085 core::hint::spin_loop();
1086 }
1087 let idx = ADDED.len.load(Ordering::Relaxed);
1088 let installed = if idx < MAX_ADDED_SINKS {
1089 // SAFETY: `ADD_LOCK` makes this the only writer, `idx` is beyond what
1090 // any reader may look at until the `Release` store below publishes it,
1091 // and the slot is never written again.
1092 unsafe {
1093 ADDED
1094 .slots
1095 .get()
1096 .cast::<Option<&'static dyn LogSink>>()
1097 .add(idx)
1098 .write(Some(sink));
1099 }
1100 ADDED.len.store(idx + 1, Ordering::Release);
1101 true
1102 } else {
1103 false
1104 };
1105 ADD_LOCK.store(false, Ordering::Release);
1106
1107 if installed {
1108 // The first delivery target in the program replays what was held
1109 // before it. AFTER publishing, for the reason `init` states.
1110 deliver_held();
1111 }
1112 installed
1113}
1114
1115/// How many sinks [`add_sink`] has installed.
1116#[must_use]
1117pub fn added_sink_count() -> usize {
1118 ADDED.len.load(Ordering::Acquire)
1119}
1120
1121/// Hand `record` to every sink installed by [`add_sink`]. Returns how many
1122/// saw it.
1123fn deliver_to_added(record: &Record<'_>, reentrant: bool) -> usize {
1124 let len = ADDED.len.load(Ordering::Acquire);
1125 let base = ADDED.slots.get().cast::<Option<&'static dyn LogSink>>();
1126 for idx in 0..len {
1127 // SAFETY: `idx < len`, and the `Acquire` load above pairs with the
1128 // `Release` store in `add_sink` that published slot `idx`. Slots below
1129 // `len` are immutable for the rest of the program.
1130 if let Some(sink) = unsafe { base.add(idx).read() }
1131 && sink.reentrant() == reentrant
1132 {
1133 sink.log(record);
1134 }
1135 }
1136 len
1137}
1138
1139/// Whether [`__timestamp_ns`] can answer with a real clock.
1140///
1141/// `false` means every `Record::timestamp_ns` is `0` and anything DERIVED from
1142/// the timestamp — the throttle windows above all of them — has no time base:
1143/// a throttled site then emits its FIRST record and nothing after it (a clock
1144/// that never moves is a window that never elapses). Exposed so a
1145/// wrapper can say so out loud instead of degrading quietly: without this, a
1146/// throttled C call site looks identical whether it is rate-limiting or
1147/// permanently shut.
1148#[must_use]
1149pub const fn timestamp_available() -> bool {
1150 cfg!(nros_log_clock)
1151}
1152
1153/// Current monotonic time for `Record::timestamp_ns`.
1154///
1155/// With the platform clock (`cfg(nros_log_clock)`: the lane's platform
1156/// declares `[capabilities] clock = true`, or the `platform-clock` feature
1157/// pulled a port in — see `build.rs`) this reads
1158/// `nros_platform_clock_ns` — the universal per-platform export the
1159/// executor's timer accounting already links. Without it it returns `0`
1160/// ("unavailable") and imposes no link-time requirement.
1161///
1162/// Public because the emission macros expand it in user crates; not
1163/// part of the supported API surface.
1164#[doc(hidden)]
1165#[must_use]
1166pub fn __timestamp_ns() -> u64 {
1167 #[cfg(nros_log_clock)]
1168 {
1169 unsafe extern "C" {
1170 fn nros_platform_clock_ns() -> u64;
1171 }
1172 // SAFETY: bare query of the platform's monotonic us counter;
1173 // the symbol comes from whichever `nros-platform-<rtos>` port
1174 // linked the binary (the contract `PlatformSink ->
1175 // nros_platform_log_write` already relies on).
1176 unsafe { nros_platform_clock_ns() }
1177 }
1178 #[cfg(not(nros_log_clock))]
1179 {
1180 0
1181 }
1182}
1183
1184fn dispatch_to_sinks(record: &Record<'_>) {
1185 if !has_destination() {
1186 // Nothing installed yet — HOLD the record; `init` replays it into
1187 // whatever sinks the board chooses. See `early` for why this crate
1188 // does not reach for the platform sink itself: doing that (issue 0710)
1189 // put `nros_platform_log_write` on a path every binary executes, which
1190 // turned a pluggable delivery into a link-time requirement that no
1191 // Cargo feature can undo under workspace feature unification.
1192 //
1193 // It is also a better answer to issue 0708 than installing a default
1194 // was: the early records land in the sink the board picked, not in the
1195 // one dispatch guessed before the board had spoken.
1196 early::hold(record, early::Owed::All);
1197 return;
1198 }
1199 // Issue 2762 -- the re-entrant sinks first, in this context, with no
1200 // guard: they are what concurrent loggers must not queue for. Past the
1201 // depth bound (a re-entrant sink logging, or that many contexts inside
1202 // one at once) the record takes the guarded path for every sink.
1203 let owed = if REENTRANT_ACTIVE.fetch_add(1, Ordering::AcqRel) < REENTRANT_DEPTH {
1204 deliver_to(record, early::Owed::All, Reentrancy::Reentrant);
1205 REENTRANT_ACTIVE.fetch_sub(1, Ordering::AcqRel);
1206 early::Owed::Serialised
1207 } else {
1208 REENTRANT_ACTIVE.fetch_sub(1, Ordering::AcqRel);
1209 early::Owed::All
1210 };
1211 if !dispatch_guard_try_acquire() {
1212 // Another delivery is in progress — this thread's own sink logging
1213 // (recursion), or another thread. Hold it for the sinks it still
1214 // owes, then take the hand-off (`early` module docs, issue 2000).
1215 early::hold(record, owed);
1216 if dispatch_guard_try_acquire() {
1217 drain_and_release();
1218 }
1219 return;
1220 }
1221 deliver(record, owed);
1222 drain_and_release();
1223}
1224
1225/// Which sinks one call of [`deliver_to`] reaches.
1226#[derive(Clone, Copy, PartialEq, Eq)]
1227enum Reentrancy {
1228 /// The re-entrant ones only (no guard needed).
1229 Reentrant,
1230 /// The others only (guard held).
1231 Serialised,
1232}
1233
1234/// Every sink `owed` names, with the guard held: the serialised sinks, and
1235/// the re-entrant ones too when the record never reached them.
1236fn deliver(record: &Record<'_>, owed: early::Owed) {
1237 if owed == early::Owed::All {
1238 deliver_to(record, owed, Reentrancy::Reentrant);
1239 }
1240 deliver_to(record, owed, Reentrancy::Serialised);
1241}
1242
1243/// A HELD record, from the drain, with the guard held.
1244///
1245/// A record held for every sink is held because the re-entrant depth was
1246/// spent -- a re-entrant sink logging from inside its own `log()`, or that
1247/// many contexts in one at once. Its re-entrant delivery here counts as the
1248/// whole depth, so whatever the sink logs from inside it is held rather than
1249/// delivered on top of it: a re-entrant sink that logs is then bounded by the
1250/// drain passes, exactly as a serialised one is. Only held records pay this;
1251/// it would otherwise stall every other context's direct delivery.
1252fn deliver_held_record(record: &Record<'_>, owed: early::Owed) {
1253 if owed == early::Owed::All {
1254 REENTRANT_ACTIVE.fetch_add(REENTRANT_DEPTH, Ordering::AcqRel);
1255 HOLDER_SPENT_DEPTH.store(true, Ordering::SeqCst);
1256 deliver_to(record, owed, Reentrancy::Reentrant);
1257 return_holder_depth();
1258 }
1259 deliver_to(record, owed, Reentrancy::Serialised);
1260}
1261
1262/// Whether the guard's holder has spent the whole re-entrant depth on a held
1263/// record ([`deliver_held_record`]) and not yet given it back. Only the holder
1264/// sets it, so it belongs to whoever holds the guard: a holder that dies inside
1265/// that delivery leaves it set, and [`release_dead_dispatch_holder`] gives the
1266/// depth back with the guard (issues 2738 and 2762). Without that, every later
1267/// record would take the guarded path for good.
1268static HOLDER_SPENT_DEPTH: AtomicBool = AtomicBool::new(false);
1269
1270/// Give back the depth [`deliver_held_record`] spent, exactly once, whether
1271/// the holder returns or a fault handler releases a dead one.
1272fn return_holder_depth() {
1273 if HOLDER_SPENT_DEPTH.swap(false, Ordering::SeqCst) {
1274 REENTRANT_ACTIVE.fetch_sub(REENTRANT_DEPTH, Ordering::AcqRel);
1275 }
1276}
1277
1278/// Whether a delivery would reach any sink.
1279///
1280/// phase-417 W4.d — the appendable list counts as much as `init`'s: a record
1281/// with at least one destination is NOT held.
1282fn has_destination() -> bool {
1283 !SINKS_PTR.load(Ordering::Acquire).is_null() || ADDED.len.load(Ordering::Acquire) > 0
1284}
1285
1286/// Whether any sink is installed ([`init`] or [`add_sink`]).
1287///
1288/// For a boot hook that installs a DEFAULT only when nobody chose
1289/// one: a record raised with no sink is held in the early ring and reaches no
1290/// console until something installs a sink, so a hosted image that never
1291/// called a board funnel lost every framework diagnostic.
1292#[must_use]
1293pub fn sinks_installed() -> bool {
1294 has_destination()
1295}
1296
1297/// Hand `record` to every sink of one kind, appended ones first. The
1298/// serialised kind is called with the dispatch guard held.
1299fn deliver_to(record: &Record<'_>, _owed: early::Owed, kind: Reentrancy) {
1300 let want = kind == Reentrancy::Reentrant;
1301 deliver_to_added(record, want);
1302 let ptr = SINKS_PTR.load(Ordering::Acquire);
1303 if !ptr.is_null() {
1304 // SAFETY: `init` published a valid `'static` slice reference.
1305 let sinks: &'static [&'static dyn LogSink] = unsafe { *ptr };
1306 for sink in sinks {
1307 if sink.reentrant() == want {
1308 sink.log(record);
1309 }
1310 }
1311 }
1312}
1313
1314/// Deliver whatever is held, if a sink exists and no delivery is in progress.
1315/// One in progress delivers it itself before it lets go.
1316fn deliver_held() {
1317 // A loss is worth a delivery on its own: `NROS_LOG_EARLY_RECORDS = 0`
1318 // holds nothing, so the count may be all there is to report.
1319 if has_destination() && (early::pending() || lost_unreported()) && dispatch_guard_try_acquire()
1320 {
1321 drain_and_release();
1322 }
1323}
1324
1325/// With the guard held: deliver the held records, release, and take the guard
1326/// back while a record is still waiting — at most [`early::DRAIN_PASSES`]
1327/// times, which is what bounds a sink that logs (`early` module docs).
1328fn drain_and_release() {
1329 for pass in 0..early::DRAIN_PASSES {
1330 early::drain_with(&mut |record, owed| deliver_held_record(record, owed));
1331 report_lost();
1332 dispatch_guard_release();
1333 // `SeqCst` on both: a raiser that saw the guard held published its
1334 // record before retrying the guard, so either it gets the guard or
1335 // this load sees the record.
1336 if pass + 1 == early::DRAIN_PASSES || !early::pending() || !dispatch_guard_try_acquire() {
1337 break;
1338 }
1339 }
1340}
1341
1342/// Records lost to a full hold queue, already reported. Written only with the
1343/// dispatch guard held.
1344static LOST_REPORTED: AtomicUsize = AtomicUsize::new(0);
1345
1346fn lost_unreported() -> bool {
1347 early::overflowed() != LOST_REPORTED.load(Ordering::Relaxed)
1348}
1349
1350/// With the guard held: say how many records were lost since the last report.
1351///
1352/// `nros-log` cannot know what those records said, but it does know how many
1353/// there were, and a silent hole is worse than a count. Delivered directly
1354/// rather than through dispatch, because a report that could itself be held —
1355/// and so lost — would undercount the loss it exists to state.
1356fn report_lost() {
1357 let lost = early::overflowed();
1358 let reported = LOST_REPORTED.swap(lost, Ordering::Relaxed);
1359 if lost == reported || !severity_enabled_at_compile_time(Severity::Warn) {
1360 return;
1361 }
1362 let mut message = buffer::FormatBuffer::new();
1363 let _ = core::fmt::Write::write_fmt(
1364 &mut message,
1365 format_args!(
1366 "{} log record(s) lost: more were waiting for a sink than \
1367 NROS_LOG_EARLY_RECORDS = {} holds (see `nros_log::early`)",
1368 lost - reported,
1369 early::early_depth()
1370 ),
1371 );
1372 deliver(
1373 &Record {
1374 severity: Severity::Warn,
1375 logger_name: "nros_log",
1376 message: message.as_str(),
1377 file: file!(),
1378 line: line!(),
1379 timestamp_ns: __timestamp_ns(),
1380 },
1381 early::Owed::All,
1382 );
1383}
1384
1385/// Flush every registered sink, appended ones included.
1386pub fn flush() {
1387 // A record held for a busy dispatcher (issue 2000) is not flushed until it
1388 // has been delivered.
1389 deliver_held();
1390 let len = ADDED.len.load(Ordering::Acquire);
1391 let base = ADDED.slots.get().cast::<Option<&'static dyn LogSink>>();
1392 for idx in 0..len {
1393 // SAFETY: same publication invariant as `deliver_to_added`.
1394 if let Some(sink) = unsafe { base.add(idx).read() } {
1395 sink.flush();
1396 }
1397 }
1398 let ptr = SINKS_PTR.load(Ordering::Acquire);
1399 if ptr.is_null() {
1400 return;
1401 }
1402 // SAFETY: same invariant as `dispatch_to_sinks`.
1403 let sinks: &'static [&'static dyn LogSink] = unsafe { *ptr };
1404 for sink in sinks {
1405 sink.flush();
1406 }
1407}
1408
1409// -----------------------------------------------------------------------------
1410// Dispatch guard — one delivery at a time, process-wide.
1411//
1412// Held across every `sink.log()`. It breaks a sink that logs from recursing,
1413// and it keeps two threads out of the sinks at once, so a sink never sees
1414// interleaved calls. A record that finds it held is NOT dropped (issue 2000):
1415// it is held in `early` and delivered by the holder. Per-thread recursion
1416// detection would need a thread identity, which no `no_std` target here gives
1417// for free; deferral needs none.
1418// -----------------------------------------------------------------------------
1419
1420static DISPATCH_GUARD: AtomicBool = AtomicBool::new(false);
1421
1422/// Who holds [`DISPATCH_GUARD`], as the address of a stack slot in the frame
1423/// that claimed it; `0` while it is free (issue 2738).
1424///
1425/// A record that meets a held guard is handed to the HOLDER to deliver, so a
1426/// holder that never runs again (a thread that faulted inside a sink and was
1427/// aborted) strands every later record from every thread, silently. Nothing
1428/// here can see that happen, but a fault handler can: it knows the dying
1429/// thread and that thread's stack bounds, and a stack ADDRESS is an identity
1430/// every `no_std` target has for free, where a thread id is not. It is never
1431/// dereferenced. An interrupt that claims the guard leaves an address on the
1432/// interrupt stack, which no thread's stack contains, so it is never taken for
1433/// a dying thread's.
1434///
1435/// Set after the claim and cleared before the release, so it is `0` for the
1436/// two stores' width of an otherwise-held guard. A fault cannot land between
1437/// them in the claiming thread on the way to a sink.
1438static DISPATCH_HOLDER: AtomicUsize = AtomicUsize::new(0);
1439
1440fn dispatch_guard_try_acquire() -> bool {
1441 if DISPATCH_GUARD
1442 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
1443 .is_err()
1444 {
1445 return false;
1446 }
1447 let here = 0u8;
1448 DISPATCH_HOLDER.store(core::ptr::addr_of!(here) as usize, Ordering::SeqCst);
1449 true
1450}
1451
1452fn dispatch_guard_release() {
1453 DISPATCH_HOLDER.store(0, Ordering::SeqCst);
1454 DISPATCH_GUARD.store(false, Ordering::SeqCst);
1455}
1456
1457// Issue 2738.
1458/// The address of a stack slot in the frame that holds the dispatch guard, or
1459/// `0` when no delivery is in progress.
1460///
1461/// For a fault handler: if this lies inside the dying thread's stack, that
1462/// thread holds the dispatcher, and [`release_dead_dispatch_holder`] is how to
1463/// stop it stranding every later record. Lock-free, safe from any context.
1464#[must_use]
1465pub fn dispatch_holder_frame() -> usize {
1466 DISPATCH_HOLDER.load(Ordering::SeqCst)
1467}
1468
1469/// Release the dispatch guard on behalf of a holder that will never run again,
1470/// and only while `frame` (from [`dispatch_holder_frame`]) still holds it.
1471/// Returns whether it did.
1472///
1473/// Call it ONLY for a holder that is dead or about to be aborted, from the
1474/// handler that knows it: the guard exists to keep two callers out of the
1475/// sinks at once, and releasing a live holder's breaks exactly that. A dead
1476/// holder can no longer be in a sink, so the next record claims the guard,
1477/// is delivered, and delivers what was held meanwhile.
1478///
1479/// What the holder was doing is lost with it: the record it was delivering,
1480/// and, if it died while draining, the one held slot it had taken (held
1481/// records then occupy one slot fewer until reboot). A sink it died inside
1482/// sees its next call without the end of that one, so a sink that takes a
1483/// lock a dead thread can own may block where it would otherwise have been
1484/// skipped. The alternative, keeping the guard, loses EVERY later record.
1485///
1486/// A holder that died delivering a held record to a re-entrant sink had spent
1487/// the whole re-entrant depth on it; that is given back too.
1488/// A thread that dies inside a re-entrant sink's DIRECT delivery holds no
1489/// guard, so nothing here can see it: it keeps one unit of
1490/// [`REENTRANT_DEPTH`] until reboot, and once that many have died, records
1491/// take the guarded path for every sink (delivered, one at a time).
1492pub fn release_dead_dispatch_holder(frame: usize) -> bool {
1493 if frame == 0
1494 || DISPATCH_HOLDER
1495 .compare_exchange(frame, 0, Ordering::SeqCst, Ordering::SeqCst)
1496 .is_err()
1497 {
1498 return false;
1499 }
1500 return_holder_depth();
1501 DISPATCH_GUARD.store(false, Ordering::SeqCst);
1502 true
1503}
1504
1505/// C spelling of [`dispatch_holder_frame`], for a platform's fault handler
1506/// (the Zephyr port's `nros_zephyr_log_dead_holder_check`).
1507#[unsafe(no_mangle)]
1508pub extern "C" fn nros_log_dispatch_holder_frame() -> usize {
1509 dispatch_holder_frame()
1510}
1511
1512/// C spelling of [`release_dead_dispatch_holder`].
1513#[unsafe(no_mangle)]
1514pub extern "C" fn nros_log_release_dead_dispatch_holder(frame: usize) -> bool {
1515 release_dead_dispatch_holder(frame)
1516}
1517
1518// -----------------------------------------------------------------------------
1519// Tests (host-only).
1520// -----------------------------------------------------------------------------
1521
1522#[cfg(test)]
1523mod tests {
1524 use super::*;
1525
1526 #[test]
1527 fn severity_round_trips_through_u8() {
1528 for s in [
1529 Severity::Trace,
1530 Severity::Debug,
1531 Severity::Info,
1532 Severity::Warn,
1533 Severity::Error,
1534 Severity::Fatal,
1535 ] {
1536 assert_eq!(severity_from_u8(s.as_u8()), Some(s));
1537 }
1538 assert_eq!(severity_from_u8(99), None);
1539 }
1540
1541 #[test]
1542 fn logger_runtime_threshold_filters_below() {
1543 let logger = Logger::with_level("test_thresh", Severity::Warn);
1544 assert!(!logger.is_enabled(Severity::Info));
1545 assert!(logger.is_enabled(Severity::Warn));
1546 assert!(logger.is_enabled(Severity::Error));
1547 logger.set_level(Severity::Debug);
1548 assert!(logger.is_enabled(Severity::Info));
1549 }
1550
1551 /// phase-467, ledger rows `c:log_severity_t` + `rust:Logger::set_default_level`.
1552 ///
1553 /// ONE test rather than five, deliberately: the process default is
1554 /// process-wide state and `cargo test` runs this crate's tests as threads
1555 /// in one process, so a second test that moved it would race this one and
1556 /// the flake would read as a logic bug. It restores the default before it
1557 /// returns for the same reason.
1558 #[test]
1559 fn a_logger_with_no_level_of_its_own_follows_the_process_default() {
1560 assert_eq!(Logger::default_level(), Severity::Info, "starting default");
1561
1562 let unset = Logger::new("test_unset_follows_default");
1563 let stated = Logger::with_level("test_stated_keeps_its_own", Severity::Warn);
1564
1565 // Unset logger, untouched default: Info, exactly as before phase-467.
1566 assert_eq!(unset.level(), Severity::Info);
1567 assert!(!unset.is_enabled(Severity::Debug));
1568 assert!(unset.is_enabled(Severity::Info));
1569
1570 // Moving the default moves it RETROACTIVELY — the logger already
1571 // existed. This is what a re-export of `DEFAULT_LOGGER.set_level`
1572 // could not do.
1573 Logger::set_default_level(Severity::Debug);
1574 assert_eq!(Logger::default_level(), Severity::Debug);
1575 assert_eq!(unset.level(), Severity::Debug);
1576 assert!(unset.is_enabled(Severity::Debug));
1577 assert!(!unset.is_enabled(Severity::Trace));
1578
1579 // ...and does NOT override a logger that states its own level. If it
1580 // did, `with_level(.., Info)` and `new(..)` would be the same thing,
1581 // which is the distinction the sentinel exists to keep.
1582 assert_eq!(stated.level(), Severity::Warn);
1583 assert!(!stated.is_enabled(Severity::Info));
1584
1585 // Stating a level on the unset logger detaches it.
1586 unset.set_level(Severity::Error);
1587 Logger::set_default_level(Severity::Trace);
1588 assert_eq!(unset.level(), Severity::Error);
1589 assert!(!unset.is_enabled(Severity::Warn));
1590
1591 // ...and unsetting it re-attaches it, to the CURRENT default.
1592 unset.unset_level();
1593 assert_eq!(unset.level(), Severity::Trace);
1594 assert!(unset.is_enabled(Severity::Trace));
1595
1596 // The sentinel is outside `Severity`, in the direction that can only
1597 // ever SUPPRESS a record: `severity_from_u8` refuses it, and it is
1598 // above `Fatal`, not below `Trace` where rcutils's own `UNSET` sits.
1599 assert_eq!(severity_from_u8(LEVEL_UNSET), None);
1600 assert!(LEVEL_UNSET > Severity::Fatal.as_u8());
1601
1602 Logger::set_default_level(Severity::Info);
1603 }
1604
1605 #[test]
1606 fn unregistered_get_logger_returns_default() {
1607 let l = get_logger("definitely-not-registered-99");
1608 assert_eq!(l.name(), DEFAULT_LOGGER.name());
1609 }
1610
1611 #[test]
1612 fn registered_logger_round_trips_through_intern_table() {
1613 static LOGGER: Logger = Logger::new("test_intern_round_trip");
1614 let published = register_logger(&LOGGER);
1615 assert_eq!(published.name(), LOGGER.name());
1616 let looked_up = get_logger("test_intern_round_trip");
1617 assert!(core::ptr::eq(published, looked_up));
1618 }
1619
1620 #[test]
1621 fn compile_time_ceiling_matches_the_resolved_knob() {
1622 // `config::MAX_LEVEL` is `NROS_LOG_MAX_LEVEL` as `build.rs` resolved
1623 // it (builtin 0 = trace; 6 = off).
1624 let ceiling = severity_from_u8(config::MAX_LEVEL);
1625 for severity in [
1626 Severity::Trace,
1627 Severity::Debug,
1628 Severity::Info,
1629 Severity::Warn,
1630 Severity::Error,
1631 Severity::Fatal,
1632 ] {
1633 let enabled = ceiling.is_some_and(|c| severity >= c);
1634 assert_eq!(severity_enabled_at_compile_time(severity), enabled);
1635 // The ceiling bounds the runtime level: below it, no logger level
1636 // can switch a severity back on.
1637 static PROBE: Logger = Logger::with_level("ceiling_probe", Severity::Trace);
1638 assert_eq!(PROBE.is_enabled(severity), enabled);
1639 }
1640 }
1641}