返回 CodeWhale
logging.rs
根目录 / crates / runtime / src / logging.rs
1 //! Lightweight verbose logging helpers for the CLI.
2
3 use std::sync::atomic::{AtomicBool, Ordering};
4
5 use colored::Colorize;
6
7 use codewhale_palette as palette;
8 static VERBOSE: AtomicBool = AtomicBool::new(false);
9 #[cfg(windows)]
10 static VERBOSE_SNAPSHOT: AtomicBool = AtomicBool::new(false);
11
12 pub struct PhaseTimer {
13 phase: &'static str,
14 started: std::time::Instant,
15 }
16
17 impl PhaseTimer {
18 pub fn start(phase: &'static str) -> Option<Self> {
19 static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
20 ENABLED
21 .get_or_init(|| std::env::var("CODEWHALE_TIMING").is_ok_and(|value| value == "1"))
22 .then(|| Self {
23 phase,
24 started: std::time::Instant::now(),
25 })
26 }
27 }
28
29 impl Drop for PhaseTimer {
30 fn drop(&mut self) {
31 use std::io::Write;
32 let receipt = serde_json::json!({
33 "type": "execution_timing",
34 "phase": self.phase,
35 "pid": std::process::id(),
36 "elapsed_us": self.started.elapsed().as_micros(),
37 "ended_unix_us": std::time::SystemTime::now()
38 .duration_since(std::time::UNIX_EPOCH)
39 .ok()
40 .map(|elapsed| elapsed.as_micros()),
41 });
42 let _ = writeln!(std::io::stderr().lock(), "{receipt}");
43 }
44 }
45
46 /// Enable or disable verbose logging output.
47 pub fn set_verbose(enabled: bool) {
48 VERBOSE.store(enabled, Ordering::SeqCst);
49 }
50
51 /// Capture the current verbose state so the TUI can restore it after
52 /// temporarily suppressing Windows alt-screen output.
53 #[cfg(windows)]
54 pub fn snapshot_verbose_state() {
55 VERBOSE_SNAPSHOT.store(is_verbose(), Ordering::SeqCst);
56 }
57
58 /// Restore the last captured verbose state.
59 #[cfg(windows)]
60 pub fn restore_verbose_state() {
61 set_verbose(VERBOSE_SNAPSHOT.load(Ordering::SeqCst));
62 }
63
64 /// Return true when `CODEWHALE_LOG_LEVEL` (legacy alias: `DEEPSEEK_LOG_LEVEL`)
65 /// requests verbose output.
66 ///
67 /// Note: `RUST_LOG` is intentionally NOT checked here — it controls the
68 /// `tracing` subscriber filter in `runtime_log.rs` (file logging) and
69 /// should not gate CLI verbose output. On Windows, where stderr is not
70 /// redirected to the log file, coupling the two causes tracing log
71 /// messages to leak into the TUI alt-screen.
72 #[must_use]
73 pub fn env_requests_verbose_logging() -> bool {
74 std::env::var("CODEWHALE_LOG_LEVEL")
75 .or_else(|_| std::env::var("DEEPSEEK_LOG_LEVEL"))
76 .ok()
77 .is_some_and(|value| log_value_enables_verbose(&value))
78 }
79
80 fn log_value_enables_verbose(value: &str) -> bool {
81 value.split(',').any(|directive| {
82 let level = directive
83 .rsplit('=')
84 .next()
85 .unwrap_or(directive)
86 .trim()
87 .to_ascii_lowercase();
88 matches!(level.as_str(), "trace" | "debug" | "info")
89 })
90 }
91
92 /// Check whether verbose logging is enabled.
93 #[must_use]
94 pub fn is_verbose() -> bool {
95 VERBOSE.load(Ordering::SeqCst)
96 }
97
98 /// Emit a verbose info message (no-op when verbosity is disabled).
99 pub fn info(message: impl AsRef<str>) {
100 if is_verbose() {
101 let (r, g, b) = palette::WHALE_ACTION_RGB;
102 eprintln!("{} {}", "info".truecolor(r, g, b).bold(), message.as_ref());
103 }
104 }
105
106 /// Emit a verbose warning message (no-op when verbosity is disabled).
107 pub fn warn(message: impl AsRef<str>) {
108 if is_verbose() {
109 let (r, g, b) = palette::WHALE_ACTION_RGB;
110 eprintln!("{} {}", "warn".truecolor(r, g, b).bold(), message.as_ref());
111 }
112 }
113
114 #[cfg(test)]
115 #[cfg(windows)]
116 mod tests {
117 use super::*;
118 use std::sync::Mutex;
119
120 static TEST_GUARD: Mutex<()> = Mutex::new(());
121
122 #[test]
123 fn log_value_parser_accepts_common_rust_log_directives() {
124 assert!(log_value_enables_verbose("debug"));
125 assert!(log_value_enables_verbose("codewhale_cli=debug"));
126 assert!(log_value_enables_verbose(
127 "warn,codewhale_runtime::client=trace"
128 ));
129 assert!(!log_value_enables_verbose("warn"));
130 assert!(!log_value_enables_verbose("codewhale_runtime=off"));
131 }
132
133 #[test]
134 fn snapshot_and_restore_verbose_state_round_trip() {
135 let _guard = TEST_GUARD.lock().unwrap_or_else(|err| err.into_inner());
136
137 set_verbose(false);
138 snapshot_verbose_state();
139 set_verbose(true);
140 restore_verbose_state();
141 assert!(!is_verbose());
142
143 set_verbose(true);
144 snapshot_verbose_state();
145 set_verbose(false);
146 restore_verbose_state();
147 assert!(is_verbose());
148
149 set_verbose(false);
150 }
151
152 #[test]
153 fn restore_keeps_cli_verbose_state_even_when_env_is_not_verbose() {
154 let _guard = TEST_GUARD.lock().unwrap_or_else(|err| err.into_inner());
155
156 set_verbose(true);
157 snapshot_verbose_state();
158
159 // Simulate the Windows alt-screen suppression path. The restore must
160 // bring back the pre-suppression CLI state without depending on the
161 // environment.
162 set_verbose(false);
163 restore_verbose_state();
164
165 assert!(is_verbose());
166 set_verbose(false);
167 }
168 }
169
169 lines RUST