Skip to main content

ant_node/
logging.rs

1//! Logging facade that compiles to no-ops when the `logging` feature is disabled.
2//!
3//! When the `logging` feature is enabled, this module re-exports the
4//! [`tracing`] macros (`info!`, `warn!`, `debug!`, `error!`, `trace!`).
5//!
6//! When disabled, all macros expand to `()` — zero binary size overhead,
7//! zero runtime cost. Argument expressions are **not evaluated**, so
8//! `info!("{}", expensive_call())` costs nothing in release builds.
9//!
10//! ## Unused variables with `--no-default-features`
11//!
12//! Variables that exist only for logging (e.g. `let addr_hex = hex::encode(...)`)
13//! become unused when macros are compiled out. The crate-level attribute
14//! `#![cfg_attr(not(feature = "logging"), allow(unused_variables, unused_assignments))]`
15//! in `lib.rs` (and the binary entry points) suppresses these expected warnings.
16
17// ---- Feature enabled: re-export tracing ----
18#[cfg(feature = "logging")]
19pub use tracing::{debug, enabled, error, info, trace, warn, Level};
20
21// ---- Feature disabled: no-op macros ----
22//
23// `#[macro_export]` places macros at the crate root. We use prefixed names
24// to avoid clashing with built-in attributes (e.g. `warn`), then re-export
25// them here under the expected names.
26
27#[cfg(not(feature = "logging"))]
28#[macro_export]
29#[doc(hidden)]
30macro_rules! __log_noop_info {
31    ($($arg:tt)*) => {
32        ()
33    };
34}
35
36#[cfg(not(feature = "logging"))]
37#[macro_export]
38#[doc(hidden)]
39macro_rules! __log_noop_warn {
40    ($($arg:tt)*) => {
41        ()
42    };
43}
44
45#[cfg(not(feature = "logging"))]
46#[macro_export]
47#[doc(hidden)]
48macro_rules! __log_noop_debug {
49    ($($arg:tt)*) => {
50        ()
51    };
52}
53
54#[cfg(not(feature = "logging"))]
55#[macro_export]
56#[doc(hidden)]
57macro_rules! __log_noop_error {
58    ($($arg:tt)*) => {
59        ()
60    };
61}
62
63#[cfg(not(feature = "logging"))]
64#[macro_export]
65#[doc(hidden)]
66macro_rules! __log_noop_trace {
67    ($($arg:tt)*) => {
68        ()
69    };
70}
71
72#[cfg(not(feature = "logging"))]
73#[macro_export]
74#[doc(hidden)]
75macro_rules! __log_noop_enabled {
76    ($($arg:tt)*) => {
77        false
78    };
79}
80
81// Re-export under short names so `use crate::logging::info;` works.
82#[cfg(not(feature = "logging"))]
83pub use __log_noop_debug as debug;
84#[cfg(not(feature = "logging"))]
85pub use __log_noop_enabled as enabled;
86#[cfg(not(feature = "logging"))]
87pub use __log_noop_error as error;
88#[cfg(not(feature = "logging"))]
89pub use __log_noop_info as info;
90#[cfg(not(feature = "logging"))]
91pub use __log_noop_trace as trace;
92#[cfg(not(feature = "logging"))]
93pub use __log_noop_warn as warn;
94
95/// Stub for `tracing::Level` when logging is disabled.
96#[cfg(not(feature = "logging"))]
97#[allow(dead_code)]
98pub struct Level;
99
100#[cfg(not(feature = "logging"))]
101#[allow(dead_code)]
102impl Level {
103    /// Debug level stub.
104    pub const DEBUG: Self = Self;
105    /// Info level stub.
106    pub const INFO: Self = Self;
107    /// Warn level stub.
108    pub const WARN: Self = Self;
109    /// Error level stub.
110    pub const ERROR: Self = Self;
111    /// Trace level stub.
112    pub const TRACE: Self = Self;
113}
114
115// ---- Build-info stamp for JSON logs ----
116
117/// JSON tail spliced onto every event: `,"node_version":"…","node_commit":"…"}`.
118///
119/// Both values are compile-time constants of the binary writing the line, so
120/// after an auto-upgrade restart the new process stamps its own version with
121/// no runtime state involved. Neither value can contain a quote or backslash
122/// (Cargo validates the version as semver; the commit is `git rev-parse
123/// --short` or the literal `unknown`), so no escaping is needed.
124#[cfg(feature = "logging")]
125const BUILD_INFO_TAIL: &str = concat!(
126    ",\"node_version\":\"",
127    env!("CARGO_PKG_VERSION"),
128    "\",\"node_commit\":\"",
129    env!("ANT_GIT_COMMIT"),
130    "\"}"
131);
132
133/// Event formatter that stamps `node_version` and `node_commit` onto every
134/// JSON log line produced by the wrapped formatter.
135///
136/// Telemetry needs the running build on *every* document, not just the
137/// startup line: a staged rollout is only readable if each log line can be
138/// attributed to the build that wrote it. `tracing_subscriber`'s JSON
139/// formatter has no hook for constant fields and span fields do not survive
140/// `tokio::spawn`, so this wraps the formatter instead: the inner output is
141/// rendered into a thread-local buffer, its closing brace is replaced with
142/// `BUILD_INFO_TAIL`, and the result is copied to the real writer. Cost is
143/// one memcpy per line on top of the serialisation the inner formatter
144/// already does.
145///
146/// Only meaningful around a JSON formatter. If the inner output does not end
147/// in `}` it is passed through untouched rather than corrupted.
148#[cfg(feature = "logging")]
149pub struct WithBuildInfo<F>(pub F);
150
151#[cfg(feature = "logging")]
152impl<S, N, F> tracing_subscriber::fmt::FormatEvent<S, N> for WithBuildInfo<F>
153where
154    S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
155    N: for<'a> tracing_subscriber::fmt::FormatFields<'a> + 'static,
156    F: tracing_subscriber::fmt::FormatEvent<S, N>,
157{
158    fn format_event(
159        &self,
160        ctx: &tracing_subscriber::fmt::FmtContext<'_, S, N>,
161        mut writer: tracing_subscriber::fmt::format::Writer<'_>,
162        event: &tracing::Event<'_>,
163    ) -> std::fmt::Result {
164        use std::cell::RefCell;
165        use tracing_subscriber::fmt::format::Writer;
166
167        thread_local! {
168            static BUF: RefCell<String> = const { RefCell::new(String::new()) };
169        }
170
171        let render = |buf: &mut String| -> std::fmt::Result {
172            buf.clear();
173            self.0.format_event(ctx, Writer::new(buf), event)
174        };
175
176        // Re-entrancy (an event emitted while formatting an event) would find
177        // the buffer already borrowed; fall back to a fresh allocation for that
178        // one line rather than panic.
179        let stamped = BUF.with(|cell| {
180            let mut buf = cell.try_borrow_mut().ok()?;
181            Some(render(&mut buf).and_then(|()| stamp_build_info(&mut writer, &buf)))
182        });
183        if let Some(result) = stamped {
184            return result;
185        }
186        let mut buf = String::new();
187        render(&mut buf)?;
188        stamp_build_info(&mut writer, &buf)
189    }
190}
191
192/// Copy `rendered` to `writer`, replacing its closing brace with
193/// [`BUILD_INFO_TAIL`]. Output that is not a JSON object is copied verbatim.
194#[cfg(feature = "logging")]
195fn stamp_build_info(
196    writer: &mut tracing_subscriber::fmt::format::Writer<'_>,
197    rendered: &str,
198) -> std::fmt::Result {
199    let body = rendered.trim_end();
200    let Some(open) = body.strip_suffix('}') else {
201        return writer.write_str(rendered);
202    };
203    // An empty object needs no leading comma before the first field.
204    let tail = if open.ends_with('{') {
205        &BUILD_INFO_TAIL[1..]
206    } else {
207        BUILD_INFO_TAIL
208    };
209    writer.write_str(open)?;
210    writer.write_str(tail)?;
211    writer.write_char('\n')
212}
213
214#[cfg(all(test, feature = "logging"))]
215#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
216mod tests {
217    use super::WithBuildInfo;
218    use std::sync::{Arc, Mutex};
219    use tracing_subscriber::fmt;
220    use tracing_subscriber::fmt::writer::{MakeWriter, MutexGuardWriter};
221    use tracing_subscriber::prelude::*;
222
223    /// Shared in-memory sink so the test can read back what the layer wrote.
224    #[derive(Clone, Default)]
225    struct Sink(Arc<Mutex<Vec<u8>>>);
226
227    impl<'a> MakeWriter<'a> for Sink {
228        type Writer = MutexGuardWriter<'a, Vec<u8>>;
229
230        fn make_writer(&'a self) -> Self::Writer {
231            self.0.make_writer()
232        }
233    }
234
235    /// Run `emit` under a JSON subscriber wrapped in `WithBuildInfo` and
236    /// return the captured lines parsed as JSON objects.
237    fn capture(
238        with_current_span: bool,
239        emit: impl FnOnce(),
240    ) -> Vec<serde_json::Map<String, serde_json::Value>> {
241        let sink = Sink::default();
242        let layer = fmt::layer()
243            .json()
244            .with_writer(sink.clone())
245            .event_format(WithBuildInfo(
246                fmt::format()
247                    .json()
248                    .flatten_event(true)
249                    .with_current_span(with_current_span),
250            ));
251        let subscriber = tracing_subscriber::registry().with(layer);
252        tracing::subscriber::with_default(subscriber, emit);
253
254        let bytes = sink.0.lock().expect("sink poisoned").clone();
255        let text = String::from_utf8(bytes).expect("log output is not UTF-8");
256        text.lines()
257            .map(|line| {
258                serde_json::from_str::<serde_json::Value>(line)
259                    .unwrap_or_else(|e| panic!("line is not valid JSON ({e}): {line}"))
260                    .as_object()
261                    .cloned()
262                    .unwrap_or_else(|| panic!("line is not a JSON object: {line}"))
263            })
264            .collect()
265    }
266
267    fn assert_stamped(doc: &serde_json::Map<String, serde_json::Value>) {
268        assert_eq!(
269            doc.get("node_version").and_then(|v| v.as_str()),
270            Some(env!("CARGO_PKG_VERSION"))
271        );
272        assert_eq!(
273            doc.get("node_commit").and_then(|v| v.as_str()),
274            Some(env!("ANT_GIT_COMMIT"))
275        );
276    }
277
278    #[test]
279    fn stamps_every_line_and_keeps_existing_fields() {
280        let docs = capture(false, || {
281            tracing::info!(peer = "12D3KooW", count = 3, "first");
282            tracing::warn!("second");
283        });
284        assert_eq!(docs.len(), 2, "one JSON line per event");
285
286        assert_stamped(&docs[0]);
287        assert_eq!(docs[0]["message"], "first");
288        assert_eq!(docs[0]["level"], "INFO");
289        assert_eq!(docs[0]["peer"], "12D3KooW");
290        assert_eq!(docs[0]["count"], 3);
291        assert!(docs[0].contains_key("timestamp"));
292        assert!(docs[0].contains_key("target"));
293
294        assert_stamped(&docs[1]);
295        assert_eq!(docs[1]["message"], "second");
296        assert_eq!(docs[1]["level"], "WARN");
297    }
298
299    #[test]
300    fn stamps_when_the_last_inner_entry_is_a_nested_object() {
301        // With `with_current_span`, the JSON formatter ends the object with a
302        // nested `"span":{...}` entry, so the splice must land after the
303        // outer brace, not the inner one.
304        let docs = capture(true, || {
305            let span = tracing::info_span!("handler", request = 7);
306            let _guard = span.enter();
307            tracing::info!("inside span");
308        });
309        assert_eq!(docs.len(), 1);
310        assert_stamped(&docs[0]);
311        assert_eq!(docs[0]["span"]["name"], "handler");
312        assert_eq!(docs[0]["span"]["request"], 7);
313    }
314
315    #[test]
316    fn version_matches_the_crate_version() {
317        // The stamp must be the build's own version — the whole point is that
318        // a freshly upgraded binary reports itself, not a provisioned string.
319        let docs = capture(false, || tracing::info!("v"));
320        let stamped = docs[0]["node_version"].as_str().expect("string");
321        assert_eq!(stamped, env!("CARGO_PKG_VERSION"));
322        assert!(
323            semver::Version::parse(stamped).is_ok(),
324            "node_version should be a semver string: {stamped}"
325        );
326    }
327}