Skip to main content

aimdb_core/
log.rs

1//! Crate-private logging macros.
2//!
3//! `log_trace!`/`log_debug!`/`log_info!`/`log_warn!`/`log_error!` forward to every enabled
4//! *destination* — the `tracing` event macro under the `tracing` feature, the
5//! `log` crate under the `log` feature, `defmt` under the `defmt` feature — and
6//! otherwise expand to a no-op that still borrows the arguments, so call sites
7//! compile identically (no unused-variable warnings) under every feature
8//! combination. This replaces the per-call-site `#[cfg(feature = "tracing")]`
9//! gates.
10//!
11//! Notes:
12//! - The no-op branch *borrows* (and therefore evaluates) the arguments — keep
13//!   them cheap (getters, lengths, references), never allocate in hot paths.
14//! - `target: <const &str>,` before the format string sets the `tracing` /
15//!   `log` target (default: the calling module, as both crates do). Events
16//!   reported from a central `events.rs` pass the module that raised them, so
17//!   per-module target filters keep matching. `defmt` has no runtime target
18//!   and ignores it: `DEFMT_LOG` filters on the expanding module.
19//! - Under `defmt`, every argument must implement `defmt::Format` (the format
20//!   strings are shared: `defmt` reads `{}` and `{:?}` alike). Core's own
21//!   types do (#352); a crate logging its own types derives or implements
22//!   `Format` for them under its `defmt` feature, and wraps a foreign type in
23//!   [`LogDisplay`] / [`LogDebug`].
24//!
25//! # Mirroring the feature
26//!
27//! These macros are `#[macro_export]`ed, so `#[cfg(feature = ...)]` inside them
28//! resolves against the *calling* crate. A crate expanding the facade must
29//! declare a feature of the same name and forward it, or its events silently go
30//! nowhere:
31//!
32//! ```toml
33//! tracing = ["aimdb-core/tracing"]               # no `dep:tracing`
34//! log     = ["aimdb-core/log"]                   # no `dep:log`
35//! defmt   = ["dep:defmt", "aimdb-core/defmt"]    # `dep:defmt` required
36//! ```
37//!
38//! `tracing` and `log` need no dependency declared: both arms go through
39//! `$crate::__private`. `defmt` does: its macros expand to absolute `defmt::`
40//! paths, so the calling crate needs `defmt` itself. The *feature* is what
41//! cannot be dropped — a `#[cfg]` in a `#[macro_export]`ed macro is resolved
42//! where it expands, so a crate without it would emit nothing.
43//!
44//! That is not a silent failure any more: an undeclared feature name makes
45//! `unexpected_cfgs` fire at every call site, which is a warning in an ordinary
46//! build and an error under `-D warnings`, as `make clippy` runs it. A dropped
47//! mirror therefore breaks CI rather than quietly muting a crate.
48//! `aimdb-sync/tests/log_facade.rs` additionally proves delivery end to end.
49//!
50//! A crate that never builds with `defmt` (a `std`-only connector) declares the
51//! name instead, so the `defmt` arm's `#[cfg]` is known to the lint:
52//!
53//! ```toml
54//! [lints.rust]
55//! unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("defmt"))'] }
56//! ```
57
58#[macro_export]
59macro_rules! log_trace {
60    (target: $t:expr, $s:literal $(, $x:expr)* $(,)?) => {{
61        let _: &str = $t;
62        #[cfg(feature = "tracing")]
63        $crate::__private::tracing::trace!(target: $t, $s $(, $x)*);
64        #[cfg(feature = "log")]
65        $crate::__private::log::trace!(target: $t, $s $(, $x)*);
66        #[cfg(feature = "defmt")]
67        ::defmt::trace!($s $(, $x)*);
68        #[cfg(not(any(feature = "tracing", feature = "log", feature = "defmt")))]
69        { let _ = ($( & $x ),*); }
70    }};
71    ($s:literal $(, $x:expr)* $(,)?) => {
72        $crate::log_trace!(target: ::core::module_path!(), $s $(, $x)*)
73    };
74}
75
76#[macro_export]
77macro_rules! log_debug {
78    (target: $t:expr, $s:literal $(, $x:expr)* $(,)?) => {{
79        let _: &str = $t;
80        #[cfg(feature = "tracing")]
81        $crate::__private::tracing::debug!(target: $t, $s $(, $x)*);
82        #[cfg(feature = "log")]
83        $crate::__private::log::debug!(target: $t, $s $(, $x)*);
84        #[cfg(feature = "defmt")]
85        ::defmt::debug!($s $(, $x)*);
86        #[cfg(not(any(feature = "tracing", feature = "log", feature = "defmt")))]
87        { let _ = ($( & $x ),*); }
88    }};
89    ($s:literal $(, $x:expr)* $(,)?) => {
90        $crate::log_debug!(target: ::core::module_path!(), $s $(, $x)*)
91    };
92}
93
94#[macro_export]
95macro_rules! log_info {
96    (target: $t:expr, $s:literal $(, $x:expr)* $(,)?) => {{
97        let _: &str = $t;
98        #[cfg(feature = "tracing")]
99        $crate::__private::tracing::info!(target: $t, $s $(, $x)*);
100        #[cfg(feature = "log")]
101        $crate::__private::log::info!(target: $t, $s $(, $x)*);
102        #[cfg(feature = "defmt")]
103        ::defmt::info!($s $(, $x)*);
104        #[cfg(not(any(feature = "tracing", feature = "log", feature = "defmt")))]
105        { let _ = ($( & $x ),*); }
106    }};
107    ($s:literal $(, $x:expr)* $(,)?) => {
108        $crate::log_info!(target: ::core::module_path!(), $s $(, $x)*)
109    };
110}
111
112#[macro_export]
113macro_rules! log_warn {
114    (target: $t:expr, $s:literal $(, $x:expr)* $(,)?) => {{
115        let _: &str = $t;
116        #[cfg(feature = "tracing")]
117        $crate::__private::tracing::warn!(target: $t, $s $(, $x)*);
118        #[cfg(feature = "log")]
119        $crate::__private::log::warn!(target: $t, $s $(, $x)*);
120        #[cfg(feature = "defmt")]
121        ::defmt::warn!($s $(, $x)*);
122        #[cfg(not(any(feature = "tracing", feature = "log", feature = "defmt")))]
123        { let _ = ($( & $x ),*); }
124    }};
125    ($s:literal $(, $x:expr)* $(,)?) => {
126        $crate::log_warn!(target: ::core::module_path!(), $s $(, $x)*)
127    };
128}
129
130#[macro_export]
131macro_rules! log_error {
132    (target: $t:expr, $s:literal $(, $x:expr)* $(,)?) => {{
133        let _: &str = $t;
134        #[cfg(feature = "tracing")]
135        $crate::__private::tracing::error!(target: $t, $s $(, $x)*);
136        #[cfg(feature = "log")]
137        $crate::__private::log::error!(target: $t, $s $(, $x)*);
138        #[cfg(feature = "defmt")]
139        ::defmt::error!($s $(, $x)*);
140        #[cfg(not(any(feature = "tracing", feature = "log", feature = "defmt")))]
141        { let _ = ($( & $x ),*); }
142    }};
143    ($s:literal $(, $x:expr)* $(,)?) => {
144        $crate::log_error!(target: ::core::module_path!(), $s $(, $x)*)
145    };
146}
147
148/// Logs `T` through its `Display` impl in every destination, `defmt` included
149/// (via `defmt::Display2Format`).
150///
151/// For a foreign type that does not implement `defmt::Format` in a `log_*!`
152/// call: `log_warn!("send failed: {}", LogDisplay(&e))`. The `tracing` and
153/// `log` output is unchanged; under `defmt` the text is formatted on the
154/// device, not interned, so keep it to error paths.
155pub struct LogDisplay<'a, T: ?Sized>(pub &'a T);
156
157impl<T: core::fmt::Display + ?Sized> core::fmt::Display for LogDisplay<'_, T> {
158    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
159        self.0.fmt(f)
160    }
161}
162
163#[cfg(feature = "defmt")]
164impl<T: core::fmt::Display + ?Sized> defmt::Format for LogDisplay<'_, T> {
165    fn format(&self, f: defmt::Formatter) {
166        defmt::write!(f, "{}", defmt::Display2Format(self))
167    }
168}
169
170/// Like [`LogDisplay`], through `Debug` (`{:?}`; `defmt::Debug2Format`).
171pub struct LogDebug<'a, T: ?Sized>(pub &'a T);
172
173impl<T: core::fmt::Debug + ?Sized> core::fmt::Debug for LogDebug<'_, T> {
174    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
175        self.0.fmt(f)
176    }
177}
178
179#[cfg(feature = "defmt")]
180impl<T: core::fmt::Debug + ?Sized> defmt::Format for LogDebug<'_, T> {
181    fn format(&self, f: defmt::Formatter) {
182        defmt::write!(f, "{}", defmt::Debug2Format(self))
183    }
184}