#[cfg(feature = "logging")]
pub use tracing::{debug, enabled, error, info, trace, warn, Level};
#[cfg(not(feature = "logging"))]
#[macro_export]
#[doc(hidden)]
macro_rules! __log_noop_info {
($($arg:tt)*) => {
()
};
}
#[cfg(not(feature = "logging"))]
#[macro_export]
#[doc(hidden)]
macro_rules! __log_noop_warn {
($($arg:tt)*) => {
()
};
}
#[cfg(not(feature = "logging"))]
#[macro_export]
#[doc(hidden)]
macro_rules! __log_noop_debug {
($($arg:tt)*) => {
()
};
}
#[cfg(not(feature = "logging"))]
#[macro_export]
#[doc(hidden)]
macro_rules! __log_noop_error {
($($arg:tt)*) => {
()
};
}
#[cfg(not(feature = "logging"))]
#[macro_export]
#[doc(hidden)]
macro_rules! __log_noop_trace {
($($arg:tt)*) => {
()
};
}
#[cfg(not(feature = "logging"))]
#[macro_export]
#[doc(hidden)]
macro_rules! __log_noop_enabled {
($($arg:tt)*) => {
false
};
}
#[cfg(not(feature = "logging"))]
pub use __log_noop_debug as debug;
#[cfg(not(feature = "logging"))]
pub use __log_noop_enabled as enabled;
#[cfg(not(feature = "logging"))]
pub use __log_noop_error as error;
#[cfg(not(feature = "logging"))]
pub use __log_noop_info as info;
#[cfg(not(feature = "logging"))]
pub use __log_noop_trace as trace;
#[cfg(not(feature = "logging"))]
pub use __log_noop_warn as warn;
#[cfg(not(feature = "logging"))]
#[allow(dead_code)]
pub struct Level;
#[cfg(not(feature = "logging"))]
#[allow(dead_code)]
impl Level {
pub const DEBUG: Self = Self;
pub const INFO: Self = Self;
pub const WARN: Self = Self;
pub const ERROR: Self = Self;
pub const TRACE: Self = Self;
}
#[cfg(feature = "logging")]
const BUILD_INFO_TAIL: &str = concat!(
",\"node_version\":\"",
env!("CARGO_PKG_VERSION"),
"\",\"node_commit\":\"",
env!("ANT_GIT_COMMIT"),
"\"}"
);
#[cfg(feature = "logging")]
pub struct WithBuildInfo<F>(pub F);
#[cfg(feature = "logging")]
impl<S, N, F> tracing_subscriber::fmt::FormatEvent<S, N> for WithBuildInfo<F>
where
S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
N: for<'a> tracing_subscriber::fmt::FormatFields<'a> + 'static,
F: tracing_subscriber::fmt::FormatEvent<S, N>,
{
fn format_event(
&self,
ctx: &tracing_subscriber::fmt::FmtContext<'_, S, N>,
mut writer: tracing_subscriber::fmt::format::Writer<'_>,
event: &tracing::Event<'_>,
) -> std::fmt::Result {
use std::cell::RefCell;
use tracing_subscriber::fmt::format::Writer;
thread_local! {
static BUF: RefCell<String> = const { RefCell::new(String::new()) };
}
let render = |buf: &mut String| -> std::fmt::Result {
buf.clear();
self.0.format_event(ctx, Writer::new(buf), event)
};
let stamped = BUF.with(|cell| {
let mut buf = cell.try_borrow_mut().ok()?;
Some(render(&mut buf).and_then(|()| stamp_build_info(&mut writer, &buf)))
});
if let Some(result) = stamped {
return result;
}
let mut buf = String::new();
render(&mut buf)?;
stamp_build_info(&mut writer, &buf)
}
}
#[cfg(feature = "logging")]
fn stamp_build_info(
writer: &mut tracing_subscriber::fmt::format::Writer<'_>,
rendered: &str,
) -> std::fmt::Result {
let body = rendered.trim_end();
let Some(open) = body.strip_suffix('}') else {
return writer.write_str(rendered);
};
let tail = if open.ends_with('{') {
&BUILD_INFO_TAIL[1..]
} else {
BUILD_INFO_TAIL
};
writer.write_str(open)?;
writer.write_str(tail)?;
writer.write_char('\n')
}
#[cfg(all(test, feature = "logging"))]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::WithBuildInfo;
use std::sync::{Arc, Mutex};
use tracing_subscriber::fmt;
use tracing_subscriber::fmt::writer::{MakeWriter, MutexGuardWriter};
use tracing_subscriber::prelude::*;
#[derive(Clone, Default)]
struct Sink(Arc<Mutex<Vec<u8>>>);
impl<'a> MakeWriter<'a> for Sink {
type Writer = MutexGuardWriter<'a, Vec<u8>>;
fn make_writer(&'a self) -> Self::Writer {
self.0.make_writer()
}
}
fn capture(
with_current_span: bool,
emit: impl FnOnce(),
) -> Vec<serde_json::Map<String, serde_json::Value>> {
let sink = Sink::default();
let layer = fmt::layer()
.json()
.with_writer(sink.clone())
.event_format(WithBuildInfo(
fmt::format()
.json()
.flatten_event(true)
.with_current_span(with_current_span),
));
let subscriber = tracing_subscriber::registry().with(layer);
tracing::subscriber::with_default(subscriber, emit);
let bytes = sink.0.lock().expect("sink poisoned").clone();
let text = String::from_utf8(bytes).expect("log output is not UTF-8");
text.lines()
.map(|line| {
serde_json::from_str::<serde_json::Value>(line)
.unwrap_or_else(|e| panic!("line is not valid JSON ({e}): {line}"))
.as_object()
.cloned()
.unwrap_or_else(|| panic!("line is not a JSON object: {line}"))
})
.collect()
}
fn assert_stamped(doc: &serde_json::Map<String, serde_json::Value>) {
assert_eq!(
doc.get("node_version").and_then(|v| v.as_str()),
Some(env!("CARGO_PKG_VERSION"))
);
assert_eq!(
doc.get("node_commit").and_then(|v| v.as_str()),
Some(env!("ANT_GIT_COMMIT"))
);
}
#[test]
fn stamps_every_line_and_keeps_existing_fields() {
let docs = capture(false, || {
tracing::info!(peer = "12D3KooW", count = 3, "first");
tracing::warn!("second");
});
assert_eq!(docs.len(), 2, "one JSON line per event");
assert_stamped(&docs[0]);
assert_eq!(docs[0]["message"], "first");
assert_eq!(docs[0]["level"], "INFO");
assert_eq!(docs[0]["peer"], "12D3KooW");
assert_eq!(docs[0]["count"], 3);
assert!(docs[0].contains_key("timestamp"));
assert!(docs[0].contains_key("target"));
assert_stamped(&docs[1]);
assert_eq!(docs[1]["message"], "second");
assert_eq!(docs[1]["level"], "WARN");
}
#[test]
fn stamps_when_the_last_inner_entry_is_a_nested_object() {
let docs = capture(true, || {
let span = tracing::info_span!("handler", request = 7);
let _guard = span.enter();
tracing::info!("inside span");
});
assert_eq!(docs.len(), 1);
assert_stamped(&docs[0]);
assert_eq!(docs[0]["span"]["name"], "handler");
assert_eq!(docs[0]["span"]["request"], 7);
}
#[test]
fn version_matches_the_crate_version() {
let docs = capture(false, || tracing::info!("v"));
let stamped = docs[0]["node_version"].as_str().expect("string");
assert_eq!(stamped, env!("CARGO_PKG_VERSION"));
assert!(
semver::Version::parse(stamped).is_ok(),
"node_version should be a semver string: {stamped}"
);
}
}