1#[cfg(feature = "logging")]
19pub use tracing::{debug, enabled, error, info, trace, warn, Level};
20
21#[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#[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#[cfg(not(feature = "logging"))]
97#[allow(dead_code)]
98pub struct Level;
99
100#[cfg(not(feature = "logging"))]
101#[allow(dead_code)]
102impl Level {
103 pub const DEBUG: Self = Self;
105 pub const INFO: Self = Self;
107 pub const WARN: Self = Self;
109 pub const ERROR: Self = Self;
111 pub const TRACE: Self = Self;
113}
114
115#[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#[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 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#[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 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 #[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 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 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 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}