use super::{DEFAULT_ERROR_LEVEL, LatencyUnit};
use std::{fmt::Display, time::Duration};
use tracing::{Level, Span};
pub trait OnFailure<E> {
fn on_failure(&mut self, error: &E, latency: Duration, span: &Span);
}
impl<E> OnFailure<E> for () {
#[inline]
fn on_failure(&mut self, _: &E, _: Duration, _: &Span) {}
}
impl<F, E> OnFailure<E> for F
where
F: FnMut(&E, Duration, &Span),
{
fn on_failure(&mut self, error: &E, latency: Duration, span: &Span) {
self(error, latency, span)
}
}
#[derive(Clone, Debug)]
pub struct DefaultOnFailure {
level: Level,
latency_unit: LatencyUnit,
}
impl Default for DefaultOnFailure {
fn default() -> Self {
Self {
level: DEFAULT_ERROR_LEVEL,
latency_unit: LatencyUnit::Millis,
}
}
}
impl DefaultOnFailure {
pub fn new() -> Self {
Self::default()
}
pub fn level(mut self, level: Level) -> Self {
self.level = level;
self
}
pub fn latency_unit(mut self, latency_unit: LatencyUnit) -> Self {
self.latency_unit = latency_unit;
self
}
}
macro_rules! log_pattern_match {
(
$this:expr, $span:expr, $error:expr, $latency:expr, [$($level:ident),*]
) => {
match ($this.level, $this.latency_unit) {
$(
(Level::$level, LatencyUnit::Seconds) => {
tracing::event!(
Level::$level,
done_in = format_args!("{}s", $latency.as_secs_f64()),
result = format_args!("{}", $error),
"task.failed"
);
}
(Level::$level, LatencyUnit::Millis) => {
tracing::event!(
Level::$level,
done_in = format_args!("{}ms", $latency.as_millis()),
result = format_args!("{}", $error),
"task.failed"
);
}
(Level::$level, LatencyUnit::Micros) => {
tracing::event!(
Level::$level,
done_in = format_args!("{}μs", $latency.as_micros()),
result = format_args!("{}", $error),
"task.failed"
);
}
(Level::$level, LatencyUnit::Nanos) => {
tracing::event!(
Level::$level,
done_in = format_args!("{}ns", $latency.as_nanos()),
result = format_args!("{}", $error),
"task.failed"
);
}
)*
}
};
}
impl<E: Display> OnFailure<E> for DefaultOnFailure {
fn on_failure(&mut self, error: &E, latency: Duration, _span: &Span) {
log_pattern_match!(
self,
_span,
error,
latency,
[ERROR, WARN, INFO, DEBUG, TRACE]
);
}
}