#![allow(missing_docs)]
use crate::context::Context;
#[macro_export]
macro_rules! info {
($ctx:expr, $msg:expr) => {
info!($ctx, $msg,)
};
($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{
let formatted = format!($msg, $($args),*);
let full = format!("{file}:{line}: {msg}",
file = file!(),
line = line!(),
msg = &formatted);
$ctx.emit_event($crate::EventType::Info(full));
}};
}
#[macro_export]
macro_rules! warn {
($ctx:expr, $msg:expr) => {
warn!($ctx, $msg,)
};
($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{
let formatted = format!($msg, $($args),*);
let full = format!("{file}:{line}: {msg}",
file = file!(),
line = line!(),
msg = &formatted);
$ctx.emit_event($crate::EventType::Warning(full));
}};
}
#[macro_export]
macro_rules! error {
($ctx:expr, $msg:expr) => {
error!($ctx, $msg,)
};
($ctx:expr, $msg:expr, $($args:expr),* $(,)?) => {{
let formatted = format!($msg, $($args),*);
$ctx.set_last_error(&formatted);
$ctx.emit_event($crate::EventType::Error(formatted));
}};
}
impl Context {
pub fn set_last_error(&self, error: &str) {
let mut last_error = self.last_error.write();
*last_error = error.to_string();
}
pub fn get_last_error(&self) -> String {
let last_error = &*self.last_error.read();
last_error.clone()
}
}
pub trait LogExt<T, E>
where
Self: std::marker::Sized,
{
#[track_caller]
fn log_err(self, context: &Context) -> Result<T, E>;
}
impl<T, E: std::fmt::Display> LogExt<T, E> for Result<T, E> {
#[track_caller]
fn log_err(self, context: &Context) -> Result<T, E> {
if let Err(e) = &self {
let location = std::panic::Location::caller();
let full = format!(
"{file}:{line}: {e:#}",
file = location.file(),
line = location.line(),
e = e
);
context.emit_event(crate::EventType::Warning(full));
};
self
}
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use crate::test_utils::TestContext;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_get_last_error() -> Result<()> {
let t = TestContext::new().await;
assert_eq!(t.get_last_error(), "");
error!(t, "foo-error");
assert_eq!(t.get_last_error(), "foo-error");
warn!(t, "foo-warning");
assert_eq!(t.get_last_error(), "foo-error");
info!(t, "foo-info");
assert_eq!(t.get_last_error(), "foo-error");
error!(t, "bar-error");
error!(t, "baz-error");
assert_eq!(t.get_last_error(), "baz-error");
Ok(())
}
}