aerosocket_server/
logging.rs1#[cfg(feature = "logging")]
6use tracing::{debug, error, info, trace, warn};
7
8#[macro_export]
10macro_rules! log_error {
11 ($($arg:tt)*) => {
12 #[cfg(feature = "logging")]
13 {
14 tracing::error!($($arg)*);
15 }
16 #[cfg(not(feature = "logging"))]
17 {
18 eprintln!("[ERROR] {}", format!($($arg)*));
19 }
20 };
21}
22
23#[macro_export]
25macro_rules! log_warn {
26 ($($arg:tt)*) => {
27 #[cfg(feature = "logging")]
28 {
29 tracing::warn!($($arg)*);
30 }
31 #[cfg(not(feature = "logging"))]
32 {
33 eprintln!("[WARN] {}", format!($($arg)*));
34 }
35 };
36}
37
38#[macro_export]
40macro_rules! log_info {
41 ($($arg:tt)*) => {
42 #[cfg(feature = "logging")]
43 {
44 tracing::info!($($arg)*);
45 }
46 #[cfg(not(feature = "logging"))]
47 {
48 eprintln!("[INFO] {}", format!($($arg)*));
49 }
50 };
51}
52
53#[macro_export]
55macro_rules! log_debug {
56 ($($arg:tt)*) => {
57 #[cfg(feature = "logging")]
58 {
59 tracing::debug!($($arg)*);
60 }
61 #[cfg(not(feature = "logging"))]
62 {
63 eprintln!("[DEBUG] {}", format!($($arg)*));
64 }
65 };
66}
67
68#[macro_export]
70macro_rules! log_trace {
71 ($($arg:tt)*) => {
72 #[cfg(feature = "logging")]
73 {
74 tracing::trace!($($arg)*);
75 }
76 #[cfg(not(feature = "logging"))]
77 {
78 eprintln!("[TRACE] {}", format!($($arg)*));
79 }
80 };
81}
82
83#[cfg(feature = "logging")]
85pub fn init_logging() -> Result<(), Box<dyn std::error::Error>> {
86 use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
87
88 tracing_subscriber::registry()
89 .with(tracing_subscriber::EnvFilter::new(
90 std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string()),
91 ))
92 .with(tracing_subscriber::fmt::layer())
93 .init();
94
95 Ok(())
96}
97
98#[cfg(not(feature = "logging"))]
100pub fn init_logging() -> Result<(), Box<dyn std::error::Error>> {
101 Ok(())
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 #[test]
109 fn test_logging_macros() {
110 log_info!("Test info message");
111 log_warn!("Test warning message");
112 log_error!("Test error message");
113 log_debug!("Test debug message");
114 }
115
116 #[test]
117 fn test_init_logging() {
118 assert!(init_logging().is_ok());
119 }
120}