shell_tunnel/logging.rs
1//! Logging initialization and configuration.
2//!
3//! # Why colour is off
4//!
5//! The layer below is built with `with_ansi(false)`, and that is not a style
6//! choice. The `fmt` layer colours its output whenever `tracing-subscriber`'s
7//! `ansi` feature is compiled in, and that default asks nothing about what is
8//! downstream: it does not test whether stderr is a terminal, and on Windows
9//! it does not enable the console's virtual-terminal mode either. Escapes
10//! therefore reached every consumer of the logs — the file a service
11//! definition redirects to, an agent reading the pipe, and consoles that
12//! print them literally as `←[2m` in front of every line.
13//!
14//! Colour is switched off rather than made conditional, because the condition
15//! cannot be answered honestly here. `IsTerminal` alone does not settle it on
16//! Windows, where a console handle reports as a terminal whether or not it
17//! will interpret an escape; answering it properly means enabling
18//! virtual-terminal mode through the Win32 console API and falling back when
19//! that fails — a direct platform dependency and a block of `unsafe` FFI,
20//! bought for decoration on a headless gateway whose output is read by service
21//! managers, log files and agents far more often than by a person. The one
22//! surface an operator actually reads, the startup banner, is `println!` on
23//! stdout and was never coloured.
24//!
25//! This also holds the program's own logs to the rule its command output
26//! already follows: piped output is escape-free, because that is what makes it
27//! usable as structured data.
28//!
29//! `tests/main_startup_e2e.rs::the_log_stream_carries_no_ansi_escapes` is what
30//! keeps this true. A record's *text* is identical either way, so only a real
31//! process writing to a real pipe can tell the two apart — no unit test in
32//! this module can.
33
34use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
35
36/// Initialize the logging system.
37///
38/// Uses the `RUST_LOG` environment variable for filtering. If not set,
39/// defaults to `shell_tunnel=info`.
40///
41/// Diagnostics go to stderr, which leaves stdout for the things a caller wants
42/// to read: the public URL, the API key, the command to try. Sharing one stream
43/// means `shell-tunnel --tunnel | grep "Public URL"` picks up log lines instead.
44///
45/// # Panics
46///
47/// Panics if called more than once, or if another tracing subscriber
48/// has already been set.
49pub fn init() {
50 try_init().expect("logging is initialized once, before any other subscriber is set");
51}
52
53/// Try to initialize the logging system.
54///
55/// Returns `Ok(())` if successful, or `Err` if logging has already been
56/// initialized.
57///
58/// This is the whole implementation; `init` is this plus a panic. The two used
59/// to assemble the same filter and the same layer separately, and a change to
60/// either had to be made twice — the `with_ansi(false)` above is there because
61/// that is exactly what happened once already.
62pub fn try_init() -> Result<(), tracing_subscriber::util::TryInitError> {
63 let filter =
64 EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("shell_tunnel=info"));
65
66 tracing_subscriber::registry()
67 .with(filter)
68 .with(
69 tracing_subscriber::fmt::layer()
70 .compact()
71 .with_ansi(false)
72 .with_writer(std::io::stderr),
73 )
74 .try_init()
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 /// A second `try_init` reports failure rather than panicking — the contract
82 /// `init` turns back into a panic.
83 ///
84 /// Asserting on the *second* call is what makes this independent of test
85 /// order: whether or not a subscriber was already set when this test began,
86 /// one is certainly set after the first call, so the second must be `Err`.
87 /// This used to call `try_init` twice and assert nothing at all, on the
88 /// grounds that the first call's result depends on ordering — true of the
89 /// first call, and the reason to check the second one instead.
90 #[test]
91 fn a_second_try_init_fails_instead_of_panicking() {
92 let _ = try_init();
93 assert!(
94 try_init().is_err(),
95 "a subscriber is set by now, so initializing again must report failure"
96 );
97 }
98
99 #[test]
100 fn test_logging_works() {
101 // Ensure we can emit log messages without panicking
102 let _ = try_init();
103
104 tracing::info!("test info message");
105 tracing::debug!("test debug message");
106 tracing::warn!("test warn message");
107 tracing::error!("test error message");
108 // If we get here without panicking, the test passes
109 }
110}