use sonic_rs::{JsonContainerTrait, JsonValueTrait};
use std::sync::{Arc, Mutex};
use wide_log::wide_log;
wide_log!({
"service": {
"name": null,
},
"requests": counter!,
"status": null,
});
type CaptureSlot = Arc<Mutex<Option<String>>>;
fn capture() -> (
CaptureSlot,
impl FnOnce(&wide_log::WideEvent<EventKey>) + Send + 'static,
) {
let slot: CaptureSlot = Arc::new(Mutex::new(None));
let s = slot.clone();
let emit = move |ev: &wide_log::WideEvent<EventKey>| {
*s.lock().unwrap() = Some(ev.to_json().unwrap());
};
(slot, emit)
}
fn parse(slot: &CaptureSlot) -> sonic_rs::Value {
let json = slot.lock().unwrap().clone().unwrap();
sonic_rs::from_str(&json).unwrap()
}
mod child {
use super::EventKey;
pub fn emit_all_with_format_args() -> String {
let _guard = super::WideLogGuard::builder().build();
info!("literal-only from child");
let name = "qb2";
let n = 42u64;
info!("info fmt from child: name={} n={}", name, n);
warn!("warn fmt from child: name={} n={}", name, n);
debug!("debug fmt from child: name={} n={}", name, n);
trace!("trace fmt from child: name={} n={}", name, n);
error!("error fmt from child: name={} n={}", name, n);
String::from("ok")
}
pub fn emit_into_guard_with_format_args(
emit: impl FnOnce(&wide_log::WideEvent<EventKey>) + Send + 'static,
) -> String {
let _guard = super::WideLogGuard::builder().with_emit(emit).build();
let name = "qb2";
let n = 42u64;
info!("from child info: name={} n={}", name, n);
warn!("from child warn: name={} n={}", name, n);
String::from("ok")
}
}
#[test]
fn format_arg_macros_compile_from_child_module() {
let result = child::emit_all_with_format_args();
assert_eq!(result, "ok");
}
#[test]
fn format_arg_macros_emit_formatted_strings_from_child_module() {
let (slot, emit) = capture();
child::emit_into_guard_with_format_args(emit);
let json = parse(&slot);
let log = json["log"].as_array().expect("log is an array");
let mut found_info = false;
let mut found_warn = false;
for entry in log {
let msg = entry["message"].as_str().expect("entry.message is str");
if msg == "from child info: name=qb2 n=42" {
found_info = true;
assert_eq!(entry["level"].as_str(), Some("info"));
} else if msg == "from child warn: name=qb2 n=42" {
found_warn = true;
assert_eq!(entry["level"].as_str(), Some("warn"));
}
}
assert!(found_info, "missing formatted info entry: {json}");
assert!(found_warn, "missing formatted warn entry: {json}");
}