Skip to main content

shell_tunnel/
logging.rs

1//! Logging initialization and configuration.
2
3use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
4
5/// Initialize the logging system.
6///
7/// Uses the `RUST_LOG` environment variable for filtering. If not set,
8/// defaults to `shell_tunnel=info`.
9///
10/// # Panics
11///
12/// Panics if called more than once, or if another tracing subscriber
13/// has already been set.
14pub fn init() {
15    let filter =
16        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("shell_tunnel=info"));
17
18    tracing_subscriber::registry()
19        .with(filter)
20        .with(tracing_subscriber::fmt::layer().compact())
21        .init();
22}
23
24/// Try to initialize the logging system.
25///
26/// Returns `Ok(())` if successful, or `Err` if logging has already been
27/// initialized.
28pub fn try_init() -> Result<(), tracing_subscriber::util::TryInitError> {
29    let filter =
30        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("shell_tunnel=info"));
31
32    tracing_subscriber::registry()
33        .with(filter)
34        .with(tracing_subscriber::fmt::layer().compact())
35        .try_init()
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn test_try_init_idempotent() {
44        // First call may or may not succeed depending on test order
45        let _ = try_init();
46        // Second call should return error (already initialized)
47        // or succeed if this is the first test to run
48        let _ = try_init();
49        // Either way, we shouldn't panic
50    }
51
52    #[test]
53    fn test_logging_works() {
54        // Ensure we can emit log messages without panicking
55        let _ = try_init();
56
57        tracing::info!("test info message");
58        tracing::debug!("test debug message");
59        tracing::warn!("test warn message");
60        tracing::error!("test error message");
61        // If we get here without panicking, the test passes
62    }
63}