Skip to main content

gity_daemon/
logging.rs

1use tracing::{error, warn};
2
3/// Logs an error at WARN level and returns it for optional propagation.
4/// Use this when an error should be logged but operation should continue.
5#[macro_export]
6macro_rules! log_warn {
7    ($fmt:literal, $($arg:expr),*) => {
8        |err| {
9            warn!(concat!($fmt, ": {}"), $($arg),*, err);
10            err
11        }
12    };
13    ($err:expr, $fmt:literal, $($arg:expr),*) => {
14        {
15            warn!(concat!($fmt, ": {}"), $($arg),*, $err);
16            $err
17        }
18    };
19}
20
21/// Logs an error at ERROR level for critical failures that may need attention.
22#[macro_export]
23macro_rules! log_error {
24    ($fmt:literal, $($arg:expr),*) => {
25        |err| {
26            error!(concat!($fmt, ": {}"), $($arg),*, err);
27            err
28        }
29    };
30}
31
32/// Tries an operation, logs any error at WARN level, and returns success indicator.
33#[allow(dead_code)]
34pub fn warn_on_error<E: std::fmt::Display>(result: Result<(), E>, context: &str) -> bool {
35    match result {
36        Ok(()) => true,
37        Err(err) => {
38            warn!("{}: {}", context, err);
39            false
40        }
41    }
42}
43
44/// Tries an operation, logs any error at ERROR level, and returns success indicator.
45#[allow(dead_code)]
46pub fn error_on_failure<E: std::fmt::Display>(result: Result<(), E>, context: &str) -> bool {
47    match result {
48        Ok(()) => true,
49        Err(err) => {
50            error!("{}: {}", context, err);
51            false
52        }
53    }
54}
55
56/// Logs a debug message for successful operations that may be useful for tracing.
57#[macro_export]
58macro_rules! log_success {
59    ($fmt:literal, $($arg:expr),*) => {
60        debug!($fmt, $($arg),*)
61    };
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn warn_on_error_returns_true_on_ok() {
70        let result: Result<(), &str> = Ok(());
71        assert!(warn_on_error(result, "test"));
72    }
73
74    #[test]
75    fn warn_on_error_returns_false_on_err() {
76        let result: Result<(), &str> = Err("error message");
77        assert!(!warn_on_error(result, "test"));
78    }
79
80    #[test]
81    fn error_on_failure_returns_true_on_ok() {
82        let result: Result<(), &str> = Ok(());
83        assert!(error_on_failure(result, "test"));
84    }
85
86    #[test]
87    fn error_on_failure_returns_false_on_err() {
88        let result: Result<(), &str> = Err("error message");
89        assert!(!error_on_failure(result, "test"));
90    }
91}