diff --git a/Cargo.lock b/Cargo.lock index f9cbef0e..09f09e07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7299,6 +7299,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "time", "tracing", "tracing-subscriber", "web-sys", diff --git a/crates/rake-cli/src/terminal.rs b/crates/rake-cli/src/terminal.rs index 57c0fc65..5c8ec10a 100644 --- a/crates/rake-cli/src/terminal.rs +++ b/crates/rake-cli/src/terminal.rs @@ -40,7 +40,7 @@ rake ctl [--instance UUID|application-id] [--json] [--timeout SECONDS] tasks list [--owner application|tab-N|entry-N] | tasks cancel TASK operations list|get|watch|cancel OP decisions list | decisions respond DECISION --choice CHOICE - logs list|follow | requests list | traces export [--after SEQUENCE] + logs [list|follow|--follow] | requests list | traces export [--after SEQUENCE] request JSON_MESSAGE Quit reports submission; inspect decisions and quit status while the host is still running. Mutations: [--no-wait] [--request-key KEY]. Retry the same payload and key after an uncertain response. @@ -262,8 +262,10 @@ fn parse_message(mut args: Vec) -> Result<(Message, bool)> { Message::Query(Query::Tasks { owner }) } - ("logs", "list" | "follow") | ("requests", "list") | ("traces", "export") => { - follow = action == "follow"; + ("logs", "" | "list" | "follow" | "--follow") + | ("requests", "list") + | ("traces", "export") => { + follow = matches!(action.as_str(), "follow" | "--follow"); let after = option(&mut args, "--after")? .map(|value| value.parse()) .transpose()? @@ -275,7 +277,11 @@ fn parse_message(mut args: Vec) -> Result<(Message, bool)> { _ => None, }; - Message::Query(Query::Diagnostics { after, kind }) + if topic == "logs" { + Message::Query(Query::Logs { after }) + } else { + Message::Query(Query::Diagnostics { after, kind }) + } } ("windows", "list") => Message::Query(Query::Windows {}), ("windows", "get" | "close") if args.len() == 1 => { @@ -669,6 +675,11 @@ pub(super) fn run(mut args: Vec) -> Result<()> { loop { match (&mut next_query, &last_reply) { (Query::Events { cursor }, Reply::Event(event)) => *cursor = Some(event.cursor), + (Query::Logs { after }, Reply::Logs(snapshot)) => { + if let Some(record) = snapshot.records.last() { + *after = record.sequence; + } + } (Query::Diagnostics { after, .. }, Reply::Diagnostics(snapshot)) => { if let Some(record) = snapshot.records.last() { *after = record.sequence; @@ -696,7 +707,8 @@ pub(super) fn run(mut args: Vec) -> Result<()> { let value = serde_json::to_value(&last_reply)?; let quiet = matches!(&last_reply, Reply::Event(event) if event.kind == rake_protocol::control::EventKind::Unchanged) - || matches!(&last_reply, Reply::Diagnostics(snapshot) if snapshot.records.is_empty()); + || matches!(&last_reply, Reply::Diagnostics(snapshot) if snapshot.records.is_empty()) + || matches!(&last_reply, Reply::Logs(snapshot) if snapshot.records.is_empty()); if !quiet && value != previous { print(&last_reply, compact)?; @@ -715,6 +727,35 @@ mod tests { //! Real: argument parser and shared Serde schema. Doubles: none. Requires: none. use super::*; + #[test] + fn logs_use_private_transport_tail() { + for (arguments, expected_follow) in [ + (vec!["logs"], false), + (vec!["logs", "list"], false), + (vec!["logs", "follow"], true), + (vec!["logs", "--follow"], true), + ] { + let (message, follow) = + parse_message(arguments.into_iter().map(String::from).collect()).unwrap(); + + assert!(matches!(message, Message::Query(Query::Logs { after: 0 }))); + assert_eq!(follow, expected_follow); + } + + let (message, _) = + parse_message(["logs", "list", "--after", "42"].map(String::from).to_vec()).unwrap(); + + assert!(matches!(message, Message::Query(Query::Logs { after: 42 }))); + assert!( + parse_message( + ["logs", "list", "--after", "bad"] + .map(String::from) + .to_vec() + ) + .is_err() + ); + } + #[test] fn maps_owned_addresses_and_independent_open_options() { let (message, _) = parse_message( @@ -968,6 +1009,7 @@ mod tests { request_id: 1, response: true, }, + Query::Logs { after: 0 }, Query::Diagnostics { after: 0, kind: None, diff --git a/crates/rake-diagnostics/Cargo.toml b/crates/rake-diagnostics/Cargo.toml index 48e68476..430e557a 100644 --- a/crates/rake-diagnostics/Cargo.toml +++ b/crates/rake-diagnostics/Cargo.toml @@ -21,6 +21,7 @@ tracing.workspace = true tracing-subscriber.workspace = true thiserror.workspace = true web-time.workspace = true +time = { version = "0.3", default-features = false, features = ["formatting"] } [target.'cfg(target_family = "wasm")'.dependencies] web-sys = { version = "0.3", features = ["console"] } diff --git a/crates/rake-diagnostics/src/lib.rs b/crates/rake-diagnostics/src/lib.rs index 13949396..cbace784 100644 --- a/crates/rake-diagnostics/src/lib.rs +++ b/crates/rake-diagnostics/src/lib.rs @@ -20,6 +20,9 @@ #[cfg(feature = "devtools")] pub mod http; +mod logging; + +pub use logging::MAX_LOG_RECORD_BYTES; use std::collections::{BTreeMap, VecDeque}; use std::fmt; @@ -106,7 +109,30 @@ pub struct Snapshot { pub output_dropped: u64, } +/// One redacted application log line, identical to the line sent to file output. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct LogRecord { + /// Monotonic sequence within the retained log stream. + pub sequence: u64, + /// RFC 3339 UTC timestamp, level, target, message and redacted fields, without a newline. + pub line: String, +} + +/// A bounded redacted application log tail. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct LogSnapshot { + /// At most 128 retained records, oldest first, after the requested sequence. + pub records: Vec, + /// Log records lost to eviction or contention since startup. + pub dropped: u64, + /// Output lines lost to the bounded worker queue since startup. + pub output_dropped: u64, +} + struct Buffer { + logs: VecDeque, + log_sequence: u64, + log_bytes: usize, records: VecDeque, sequence: u64, #[cfg(feature = "devtools")] @@ -120,6 +146,7 @@ struct Inner { capacity: usize, dropped: AtomicU64, output_dropped: AtomicU64, + logs_dropped: AtomicU64, started: Instant, next_span: AtomicU64, #[cfg(feature = "devtools")] @@ -142,6 +169,9 @@ impl Collector { pub fn new(capacity: usize) -> Self { Self(Arc::new(Inner { buffer: Mutex::new(Buffer { + logs: VecDeque::new(), + log_sequence: 0, + log_bytes: 0, records: VecDeque::new(), sequence: 0, #[cfg(feature = "devtools")] @@ -152,6 +182,7 @@ impl Collector { capacity, dropped: AtomicU64::new(0), output_dropped: AtomicU64::new(0), + logs_dropped: AtomicU64::new(0), started: Instant::now(), next_span: AtomicU64::new(1), #[cfg(feature = "devtools")] @@ -206,6 +237,68 @@ impl Collector { ) } + /// Copies a redacted log tail after an exclusive sequence cursor. + /// Contention returns an empty tail; retry with the same cursor. + #[must_use] + pub fn logs_after(&self, after: u64) -> LogSnapshot { + LogSnapshot { + records: self + .0 + .buffer + .try_lock() + .map(|buffer| { + buffer + .logs + .iter() + .filter(|record| record.sequence > after) + .cloned() + .collect() + }) + .unwrap_or_default(), + dropped: self.0.logs_dropped.load(Ordering::Relaxed), + output_dropped: self.0.output_dropped.load(Ordering::Relaxed), + } + } + + fn record_log(&self, line: String) { + let Ok(mut buffer) = self.0.buffer.try_lock() else { + self.0.logs_dropped.fetch_add(1, Ordering::Relaxed); + + return; + }; + + if self.0.capacity == 0 { + self.0.logs_dropped.fetch_add(1, Ordering::Relaxed); + + return; + } + + buffer.log_sequence += 1; + + let record = LogRecord { + sequence: buffer.log_sequence, + line, + }; + + let bytes = serde_json::to_vec(&record).map_or(0, |bytes| bytes.len()); + + // Keep escaped JSON comfortably below the ctl frame limit. + while buffer.logs.len() >= self.0.capacity.min(128) || buffer.log_bytes + bytes > 256 * 1024 + { + if let Some(old) = buffer.logs.pop_front() { + buffer.log_bytes = buffer + .log_bytes + .saturating_sub(serde_json::to_vec(&old).map_or(0, |bytes| bytes.len())); + self.0.logs_dropped.fetch_add(1, Ordering::Relaxed); + } else { + break; + } + } + + buffer.log_bytes += bytes; + buffer.logs.push_back(record); + } + /// Current collector clock, for development records spanning several observations. #[cfg(feature = "devtools")] #[must_use] @@ -313,7 +406,7 @@ impl Collector { /// Supplies a layer for a host-owned tracing subscriber. #[must_use] pub fn layer(&self) -> CollectorLayer { - CollectorLayer(self.clone()) + CollectorLayer(self.clone(), None) } /// Records an owned event using this collector's current tracing context. @@ -475,7 +568,7 @@ impl Visit for Fields { } /// A composable tracing layer backed by a [`Collector`]. -pub struct CollectorLayer(Collector); +pub struct CollectorLayer(Collector, Option); /// Owned causal metadata captured before asynchronous work changes context. #[derive(Clone, Debug, Default)] @@ -653,6 +746,20 @@ impl LookupSpan<'lookup>> Layer for CollectorLay context }; + let line = logging::format( + event.metadata().level().as_str(), + event.metadata().target(), + &fields.0, + &context.fields, + web_time::SystemTime::now(), + ); + + self.0.record_log(line.clone()); + + if let Some(output) = &self.1 { + output.emit(event, &fields, &line); + } + self.0.record_context( context, event.metadata().level().as_str(), @@ -711,12 +818,18 @@ pub enum SubscriberMode { Host, } +#[cfg(not(target_family = "wasm"))] +type OutputFactory = Arc Box + Send + Sync>; + /// Runner diagnostic configuration. No development control endpoint is installed. #[derive(Clone, Default)] #[must_use] pub struct DiagnosticsConfig { collector: Collector, mode: SubscriberMode, + level: Option, + #[cfg(not(target_family = "wasm"))] + output: Option, } impl DiagnosticsConfig { @@ -745,6 +858,25 @@ impl DiagnosticsConfig { self } + /// Sets the default severity. `RAKE_LOG` overrides this value when valid. + pub fn log_level(mut self, level: tracing_subscriber::filter::LevelFilter) -> Self { + self.level = Some(level); + + self + } + + /// Replaces stderr with a writer created on the bounded output worker. + /// File output uses bounded single-line records with secret-named fields redacted. + #[cfg(not(target_family = "wasm"))] + pub fn log_writer( + mut self, + writer: impl Fn() -> Box + Send + Sync + 'static, + ) -> Self { + self.output = Some(Arc::new(writer)); + + self + } + /// Installs diagnostics once. Automatic installation returns an error on conflict. /// /// # Errors @@ -757,9 +889,17 @@ impl DiagnosticsConfig { tracing::subscriber::set_global_default( Registry::default() - .with(self.collector.layer()) - .with(OutputLayer::new(self.collector.clone())?) - .with(tracing_subscriber::filter::LevelFilter::INFO), + .with(CollectorLayer( + self.collector.clone(), + Some(OutputLayer::new(self.collector.clone(), self)?), + )) + .with( + std::env::var("RAKE_LOG") + .ok() + .and_then(|level| level.parse().ok()) + .or(self.level) + .unwrap_or(tracing_subscriber::filter::LevelFilter::INFO), + ), ) .map_err(|_| DiagnosticsError::SubscriberAlreadyInstalled) } @@ -779,6 +919,7 @@ pub enum DiagnosticsError { } struct OutputLayer { + file: bool, #[cfg(all(feature = "devtools", not(target_family = "wasm")))] mirror_marker: bool, #[cfg(not(target_family = "wasm"))] @@ -788,23 +929,31 @@ struct OutputLayer { } impl OutputLayer { - fn new(collector: Collector) -> Result { + fn new(collector: Collector, config: &DiagnosticsConfig) -> Result { #[cfg(not(target_family = "wasm"))] { let (sender, receiver) = std::sync::mpsc::sync_channel::(1024); + let output = config.output.clone(); + let file = output.is_some(); + std::thread::Builder::new() .name("rake-diagnostics".into()) .spawn(move || { use std::io::Write; + let mut writer: Box = output + .map(|create| create()) + .unwrap_or_else(|| Box::new(std::io::stderr())); + for text in receiver { - let _ = writeln!(std::io::stderr().lock(), "{text}"); + let _ = writeln!(writer, "{text}"); } }) .map_err(DiagnosticsError::OutputWorker)?; Ok(Self { + file, sender, collector, #[cfg(feature = "devtools")] @@ -815,27 +964,26 @@ impl OutputLayer { #[cfg(target_family = "wasm")] { - let _ = collector; + let _ = (collector, config); - Ok(Self {}) + Ok(Self { file: false }) } } -} - -impl Layer for OutputLayer { - fn on_event(&self, event: &Event<'_>, _cx: Context<'_, S>) { - let mut fields = Fields::default(); - event.record(&mut fields); - let text = format!( - "{} {} {:?}", - event.metadata().level(), - event.metadata().target(), - fields.0 - ); + fn emit(&self, event: &Event<'_>, fields: &Fields, line: &str) { + let text = if self.file { + line.to_owned() + } else { + format!( + "{} {} {:?}", + event.metadata().level(), + event.metadata().target(), + fields.0 + ) + }; #[cfg(all(feature = "devtools", not(target_family = "wasm")))] - let text = if self.mirror_marker { + let text = if !self.file && self.mirror_marker { format!("\u{1e}RAKE_DIAGNOSTIC {text}") } else { text diff --git a/crates/rake-diagnostics/src/logging.rs b/crates/rake-diagnostics/src/logging.rs new file mode 100644 index 00000000..ac17a9c5 --- /dev/null +++ b/crates/rake-diagnostics/src/logging.rs @@ -0,0 +1,182 @@ +//! One bounded, redacted line shared by file output and control snapshots. + +use std::collections::BTreeMap; +use std::fmt::{self, Write}; + +use serde_json::Value; +use time::{OffsetDateTime, format_description::well_known::Rfc3339}; +use web_time::{SystemTime, UNIX_EPOCH}; + +/// Maximum UTF-8 bytes per application log record, including its final newline. +pub const MAX_LOG_RECORD_BYTES: usize = 4096; +const TRUNCATED: &str = "…[truncated]"; + +fn secret(key: &str) -> bool { + let key = key.to_ascii_lowercase(); + + [ + "password", + "passwd", + "secret", + "token", + "authorization", + "cookie", + "api_key", + "apikey", + "credential", + "private_key", + "session", + ] + .iter() + .any(|part| key.contains(part)) +} + +struct Line { + text: String, + truncated: bool, +} + +impl Write for Line { + fn write_str(&mut self, text: &str) -> fmt::Result { + let available = (MAX_LOG_RECORD_BYTES - 1).saturating_sub(self.text.len()); + let end = text.floor_char_boundary(available.min(text.len())); + + self.text.push_str(&text[..end]); + + if end != text.len() { + self.truncated = true; + + return Err(fmt::Error); + } + + Ok(()) + } +} + +pub(super) fn format( + level: &str, + target: &str, + fields: &BTreeMap, + context: &BTreeMap, + now: SystemTime, +) -> String { + let seconds = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(); + + let timestamp = OffsetDateTime::from_unix_timestamp(seconds.min(i64::MAX as u64) as i64) + .unwrap_or(OffsetDateTime::UNIX_EPOCH) + .format(&Rfc3339) + .unwrap_or_else(|_| "1970-01-01T00:00:00Z".into()); + + let mut line = Line { + text: String::new(), + truncated: false, + }; + + let _ = write!(line, "{timestamp} {level} {}", target.escape_debug()); + + if let Some(message) = fields.get("message").or_else(|| context.get("message")) { + let _ = write!(line, " {message}"); + } + + for (key, value) in context + .iter() + .filter(|(key, _)| !fields.contains_key(*key)) + .chain(fields) + { + if line.truncated { + break; + } + + if key == "message" { + continue; + } + + let _ = write!(line, " {}=", key.escape_debug()); + + if secret(key) { + let _ = line.write_str("[redacted]"); + } else { + let _ = write!(line, "{value}"); + } + } + + if line.truncated { + line.text.truncate( + line.text + .floor_char_boundary(MAX_LOG_RECORD_BYTES - 1 - TRUNCATED.len()), + ); + line.text.push_str(TRUNCATED); + } + + line.text +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utc_message_target_fields_and_newline_escaping() { + let fields = [ + ("message".into(), Value::from("first\nsecond\rthird")), + ("count".into(), Value::from(7)), + ("detail".into(), Value::from("a\nb")), + ] + .into(); + + let line = format( + "INFO", + "example::worker", + &fields, + &BTreeMap::new(), + UNIX_EPOCH, + ); + + assert_eq!( + line, + "1970-01-01T00:00:00Z INFO example::worker \"first\\nsecond\\rthird\" count=7 detail=\"a\\nb\"" + ); + assert_eq!(line.lines().count(), 1); + } + + #[test] + fn secret_keys_match_case_insensitive_substrings() { + for key in [ + "PASSWORD", + "user_passwd", + "clientSecret", + "access_TOKEN", + "Authorization", + "Set-Cookie", + "API_KEY", + "apiKey", + "credentials", + "PRIVATE_KEY", + "sessionId", + ] { + let fields = [(key.into(), Value::from("sensitive-value"))].into(); + + let line = format("WARN", "app", &fields, &BTreeMap::new(), UNIX_EPOCH); + + assert!(line.contains("=[redacted]"), "field {key}: {line}"); + assert!(!line.contains("sensitive-value"), "field {key}: {line}"); + } + + let fields = [("count".into(), Value::from(42))].into(); + + let line = format("INFO", "app", &fields, &BTreeMap::new(), UNIX_EPOCH); + + assert!(line.contains("count=42")); + } + + #[test] + fn truncation_is_marked_utf8_safe_and_at_most_four_kib() { + let fields = [("message".into(), Value::from("🦀".repeat(4096)))].into(); + + let line = format("INFO", "app", &fields, &BTreeMap::new(), UNIX_EPOCH); + + assert!(line.len() < MAX_LOG_RECORD_BYTES); + assert!(line.ends_with(TRUNCATED)); + assert_eq!(line.lines().count(), 1); + } +} diff --git a/crates/rake-diagnostics/src/tests.rs b/crates/rake-diagnostics/src/tests.rs index b56f3032..06fb462f 100644 --- a/crates/rake-diagnostics/src/tests.rs +++ b/crates/rake-diagnostics/src/tests.rs @@ -5,21 +5,23 @@ use tracing_subscriber::prelude::*; -use super::{Collector, OutputLayer}; +use super::{Collector, CollectorLayer, DiagnosticsConfig, OutputLayer, Registry}; #[test] fn a_full_output_queue_reports_loss_and_keeps_collecting() { let collector = Collector::new(10); let (sender, receiver) = std::sync::mpsc::sync_channel(1); - let subscriber = tracing_subscriber::registry() - .with(collector.layer()) - .with(OutputLayer { + let subscriber = tracing_subscriber::registry().with(CollectorLayer( + collector.clone(), + Some(OutputLayer { + file: false, #[cfg(feature = "devtools")] mirror_marker: false, sender, collector: collector.clone(), - }); + }), + )); tracing::subscriber::with_default(subscriber, || { tracing::info!("first"); @@ -80,3 +82,185 @@ fn crash_tail_keeps_only_bounded_structural_metadata() { .all(|item| item.level == "unknown" && item.kind == "unknown") ); } + +#[test] +fn file_output_is_concurrent_redacted_and_matches_ctl() { + use std::io::{self, Write}; + use std::sync::{Mutex, mpsc}; + use std::time::Duration; + + struct Lines(mpsc::Sender>); + + impl Write for Lines { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0.send(bytes.to_vec()).map_err(io::Error::other)?; + + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + let (sender, receiver) = mpsc::channel(); + let sender = Mutex::new(sender); + + let config = DiagnosticsConfig::new() + .log_writer(move || Box::new(Lines(sender.lock().expect("test sender").clone()))); + + let collector = config.shared_collector(); + + let subscriber = Registry::default().with(CollectorLayer( + collector.clone(), + Some(OutputLayer::new(collector.clone(), &config).expect("worker")), + )); + + let dispatch = tracing::Dispatch::new(subscriber); + + std::thread::scope(|scope| { + for _ in 0..4 { + let dispatch = dispatch.clone(); + + scope.spawn(move || { + tracing::dispatcher::with_default(&dispatch, || { + for _ in 0..20 { + tracing::warn!(token = "secret-token", "private user content"); + } + }) + }); + } + }); + + drop(config); + drop(dispatch); + + let mut output = Vec::new(); + + while let Ok(bytes) = receiver.recv_timeout(Duration::from_secs(3)) { + output.extend(bytes); + } + + let output = String::from_utf8(output).expect("UTF-8 output"); + + assert_eq!(output.lines().count(), 80); + assert!( + output + .lines() + .all(|line| line.contains(" WARN ") && line.contains("private user content")) + ); + assert!(output.contains("token=[redacted]")); + assert!(!output.contains("secret-token")); + let retained: Vec<_> = collector + .logs_after(0) + .records + .into_iter() + .map(|record| record.line) + .collect(); + + assert!(!retained.is_empty()); + assert!( + retained + .iter() + .all(|line| output.lines().any(|emitted| emitted == line)) + ); + assert_eq!(collector.snapshot().output_dropped, 0); +} + +#[test] +fn full_output_queue_drops_without_waiting() { + let (sender, _receiver) = std::sync::mpsc::sync_channel(1); + + sender.try_send("occupied".into()).expect("fill queue"); + let collector = Collector::default(); + + let layer = OutputLayer { + file: true, + sender, + collector: collector.clone(), + #[cfg(feature = "devtools")] + mirror_marker: false, + }; + + let subscriber = Registry::default().with(CollectorLayer(collector.clone(), Some(layer))); + + tracing::subscriber::with_default(subscriber, || tracing::info!("dropped")); + + assert_eq!(collector.snapshot().output_dropped, 1); +} + +#[test] +fn log_tail_preserves_loss_counts_and_cursor_after_eviction() { + let collector = Collector::new(1); + + let subscriber = Registry::default().with(collector.layer()); + + tracing::subscriber::with_default(subscriber, || { + for _ in 0..2 { + tracing::info!(target: "example::worker", "message"); + } + }); + + let snapshot = collector.logs_after(0); + + assert_eq!(snapshot.records.len(), 1); + assert_eq!(snapshot.dropped, 1); + + let next = collector.logs_after(snapshot.records[0].sequence); + + assert!(next.records.is_empty()); + assert_eq!(next.dropped, 1); + assert!( + !serde_json::to_string(&snapshot) + .expect("log JSON") + .contains("private") + ); +} + +#[test] +fn escaped_log_tail_stays_below_the_transport_budget() { + let collector = Collector::new(1024); + let subscriber = Registry::default().with(collector.layer()); + + tracing::subscriber::with_default(subscriber, || { + for _ in 0..150 { + tracing::info!("{}", "\\".repeat(8192)); + } + }); + let snapshot = collector.logs_after(0); + + assert!(snapshot.records.len() <= 128); + assert!(snapshot.dropped > 0); + assert!(serde_json::to_vec(&snapshot).expect("log snapshot").len() < 270 * 1024); + assert!( + snapshot + .records + .iter() + .all(|record| record.line.ends_with("…[truncated]")) + ); +} + +#[test] +fn development_stderr_format_is_unchanged() { + let collector = Collector::default(); + let (sender, receiver) = std::sync::mpsc::sync_channel(1); + + let output = OutputLayer { + file: false, + sender, + collector: collector.clone(), + #[cfg(feature = "devtools")] + mirror_marker: false, + }; + + let subscriber = Registry::default().with(CollectorLayer(collector, Some(output))); + + tracing::subscriber::with_default(subscriber, || { + tracing::info!(target: "app", count = 7, "hello"); + }); + + assert_eq!( + receiver.try_recv().expect("stderr line"), + "INFO app {\"count\": Number(7), \"message\": String(\"hello\")}" + ); +} diff --git a/crates/rake-protocol/src/control.rs b/crates/rake-protocol/src/control.rs index 83a47f29..20f12682 100644 --- a/crates/rake-protocol/src/control.rs +++ b/crates/rake-protocol/src/control.rs @@ -373,6 +373,11 @@ pub enum Query { /// Selects the response rather than the request body. response: bool, }, + /// Redacted formatted application logs after a log sequence. + Logs { + /// Exclusive log sequence. + after: u64, + }, /// Bounded records for logs, requests and traces with observable loss counts. Diagnostics { /// Exclusive collector sequence. @@ -415,6 +420,7 @@ impl Query { "decisions", "events", "diagnostics", + "logs", "http_body", "commands", ] @@ -547,6 +553,8 @@ pub enum Reply { Event(RuntimeEvent), /// Bounded diagnostic records, including loss counts. Diagnostics(rake_diagnostics::Snapshot), + /// Redacted application log lines, matching the file output. + Logs(rake_diagnostics::LogSnapshot), } /// Structured protocol errors; transport failures are reported separately as I/O errors. diff --git a/crates/rake-ui/src/view/paragraph/layout.rs b/crates/rake-ui/src/view/paragraph/layout.rs index 03b96d5a..782d59da 100644 --- a/crates/rake-ui/src/view/paragraph/layout.rs +++ b/crates/rake-ui/src/view/paragraph/layout.rs @@ -99,7 +99,10 @@ fn shape( { Ok(lines) => lines.into_vec(), Err(error) => { - tracing::warn!(%error, "paragraph text shaping failed"); + tracing::warn!( + error_type = std::any::type_name_of_val(&error), + "paragraph text shaping failed" + ); Vec::new() } @@ -226,7 +229,10 @@ pub(super) fn paint( ) }) { - tracing::warn!(%error, "paragraph text painting failed"); + tracing::warn!( + error_type = std::any::type_name_of_val(&error), + "paragraph text painting failed" + ); } origin.y += line.size(layout.line_height).height; diff --git a/crates/rake/examples/background.rs b/crates/rake/examples/background.rs index e52f2224..2441c6c0 100644 --- a/crates/rake/examples/background.rs +++ b/crates/rake/examples/background.rs @@ -3,6 +3,7 @@ fn main() -> Result<(), rake::AppError> { rake::App::new("example.background") .background(|runtime, cx| { + rake::info!("background application started"); // Retain the UI-loop task until it has observed this managed job and quit. let task = cx.spawn(async move |_| { if let Ok(work) = runtime.tasks().spawn("background-work", async { diff --git a/crates/rake/src/application.rs b/crates/rake/src/application.rs index 554a4e12..84c7ae9a 100644 --- a/crates/rake/src/application.rs +++ b/crates/rake/src/application.rs @@ -116,6 +116,7 @@ pub struct App { diagnostics: DiagnosticsConfig, crash_reports: crate::crash::startup::CrashReports, crash_version: Option, + logging: Option, root: Option, background: Option, main_window: Option<(WindowOptionsFactory, MainWindow)>, @@ -183,6 +184,7 @@ impl App { diagnostics: DiagnosticsConfig::new(), crash_reports: crate::crash::startup::CrashReports::default(), crash_version: None, + logging: Some(crate::logging::LogConfig::default()), root: None, background: None, main_window: None, @@ -254,6 +256,7 @@ impl App { configuration_error, diagnostics: self.diagnostics, crash_reports: self.crash_reports, + logging: self.logging, crash_version: self.crash_version, root: self.root, background: self.background, @@ -611,6 +614,27 @@ impl App { self } + /// Configures automatic logging. `RAKE_LOG` overrides the level preference. + /// The last call to this method or `without_logging` selects subscriber ownership. + pub fn logging(mut self, config: crate::logging::LogConfig) -> Self { + self.logging = Some(config); + self.diagnostics = self + .diagnostics + .subscriber(crate::diagnostics::SubscriberMode::Automatic); + + self + } + + /// Leaves output and subscriber ownership to the embedding host. + pub fn without_logging(mut self) -> Self { + self.logging = None; + self.diagnostics = self + .diagnostics + .subscriber(crate::diagnostics::SubscriberMode::Host); + + self + } + /// Configures recording and opts into waiting-record delivery before GPUI starts. /// /// Recording is on by default, with no sink and no uploads. This explicit @@ -1006,6 +1030,32 @@ impl App { return Err(AppError::MissingRoot); }; + if let Some(mut config) = self.logging.take() { + if config.level.is_none() + && let Ok(preferences) = self.platform.preferences(&self.id) + { + #[cfg(not(target_family = "wasm"))] + { + config.level = futures::executor::block_on(preferences.get("log-level")) + .ok() + .flatten(); + } + + #[cfg(target_family = "wasm")] + { + use futures::FutureExt as _; + config.level = preferences + .get("log-level") + .now_or_never() + .and_then(Result::ok) + .flatten(); + } + } + + self.diagnostics = + crate::logging::configure(self.diagnostics.clone(), &self.id, config); + } + self.diagnostics.install()?; #[cfg(target_family = "wasm")] @@ -1050,7 +1100,10 @@ impl App { application.on_open_urls(move |urls| { for url in urls { if let Err(error) = activations.receive_open_url(&url) { - crate::warn!(%error, "host URL activation rejected"); + crate::warn!( + error_type = std::any::type_name_of_val(&error), + "host URL activation rejected" + ); } } }); @@ -1086,7 +1139,10 @@ impl App { cx.update(|cx| handle_reopen(&reopen, cx)); } - Err(error) => crate::warn!(%error, "instance activation rejected"), + Err(error) => crate::warn!( + error_type = std::any::type_name_of_val(&error), + "instance activation rejected" + ), } } }) @@ -1126,7 +1182,10 @@ impl App { if let Ok(updates) = services.get::() { #[cfg(all(feature = "updates-sparkle", target_os = "macos"))] if let Err(error) = updates.initialize_sparkle_checks() { - tracing::error!(%error, "native update checks could not start"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "native update checks could not start" + ); } let executor = cx.background_executor().clone(); diff --git a/crates/rake/src/application/managed.rs b/crates/rake/src/application/managed.rs index 57422191..14dac3a7 100644 --- a/crates/rake/src/application/managed.rs +++ b/crates/rake/src/application/managed.rs @@ -116,7 +116,10 @@ fn prepare( configure(&runtime, config); if let Err(error) = crate::menus::install(runtime.router.client(), services, cx) { - tracing::error!(%error, "menu host could not start"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "menu host could not start" + ); } if config.close_policy == ClosePolicy::KeepRunning { @@ -140,7 +143,10 @@ fn prepare_background(services: &Services, config: &ManagedConfig, cx: &mut gpui configure(&runtime, config); if let Err(error) = crate::menus::install(runtime.router.client(), services, cx) { - tracing::error!(%error, "menu host could not start"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "menu host could not start" + ); } cx.set_quit_mode(gpui::QuitMode::Explicit); @@ -159,7 +165,10 @@ fn configure(runtime: &Runtime, config: &ManagedConfig) { for guard in config.quit_guards.iter().cloned() { if let Err(error) = runtime.router.quit_guard(move |context| guard(context)) { - crate::error!(%error, "managed quit guard could not be registered"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "managed quit guard could not be registered" + ); } } @@ -170,7 +179,10 @@ fn configure(runtime: &Runtime, config: &ManagedConfig) { #[cfg(all(feature = "updates-sparkle", target_os = "macos"))] if let Err(error) = runtime.router.install_sparkle() { - tracing::error!(%error, "native updater could not start"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "native updater could not start" + ); } } @@ -418,7 +430,10 @@ async fn drive( let execute = async move { if let Err(error) = router.run().await { - crate::error!(%error, "managed application driver stopped"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "managed application driver stopped" + ); } }; @@ -486,7 +501,10 @@ async fn drive( observed.reply_native_quit(false); observed.prepare_native_exit(true); } - crate::error!(%error, "managed update handoff failed; manual restart required"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "managed update handoff failed; manual restart required" + ); notify(view.as_ref(), content_changed, cx).await; break; } diff --git a/crates/rake/src/application/managed/window.rs b/crates/rake/src/application/managed/window.rs index f77d5b86..0daa6d7a 100644 --- a/crates/rake/src/application/managed/window.rs +++ b/crates/rake/src/application/managed/window.rs @@ -63,7 +63,10 @@ pub(in crate::application) fn install_main_window( if !start_hidden && let Err(error) = show_main_window(cx) { // Runtime stays alive so a tray action can retry a failed mount. - crate::error!(%error, "main window could not open"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "main window could not open" + ); } } diff --git a/crates/rake/src/control/local.rs b/crates/rake/src/control/local.rs index 612dbe2e..2f1278fe 100644 --- a/crates/rake/src/control/local.rs +++ b/crates/rake/src/control/local.rs @@ -148,7 +148,10 @@ impl LocalServer { match self.listener.accept().await { Ok((stream, _)) => return Ok(stream), Err(error) if recoverable_accept_error(&error) => { - tracing::warn!(%error, "local control accept failed; retrying"); + tracing::warn!( + error_type = std::any::type_name_of_val(&error), + "local control accept failed; retrying" + ); crate::http::sleep(Duration::from_millis(100)).await; } Err(error) => return Err(error), diff --git a/crates/rake/src/control/mod.rs b/crates/rake/src/control/mod.rs index 04781dfe..c8f22ab0 100644 --- a/crates/rake/src/control/mod.rs +++ b/crates/rake/src/control/mod.rs @@ -647,6 +647,7 @@ impl RuntimeClient { request_id, response, } => Ok(Reply::Data(self.router.http_body(request_id, response))), + Query::Logs { after } => Ok(Reply::Logs(self.router.logs(after))), Query::Diagnostics { after, kind } => Ok(Reply::Diagnostics( self.router.diagnostics(after, kind.as_deref()), )), @@ -791,10 +792,16 @@ pub(crate) async fn run_host_client( match local::LocalServer::bind_host(&client, &application_id, &local::directory()) { Ok(server) => { if let Err(error) = server.run_host(client).await { - crate::error!(%error, "Development control stopped"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "Development control stopped" + ); } } - Err(error) => crate::error!(%error, "Development control could not start"), + Err(error) => crate::error!( + error_type = std::any::type_name_of_val(&error), + "Development control could not start" + ), } } @@ -802,10 +809,16 @@ pub(crate) async fn run_host_client( match WebBridgeConfig::from_document() { Ok(Some(config)) => match WebBridge::new(config) { Ok(bridge) => bridge.run_host(client, &application_id).await, - Err(error) => crate::error!(%error, "Development bridge could not start"), + Err(error) => crate::error!( + error_type = std::any::type_name_of_val(&error), + "Development bridge could not start" + ), }, Ok(None) => {} - Err(error) => crate::error!(%error, "Invalid development bridge configuration"), + Err(error) => crate::error!( + error_type = std::any::type_name_of_val(&error), + "Invalid development bridge configuration" + ), } } diff --git a/crates/rake/src/control/web.rs b/crates/rake/src/control/web.rs index 121a9a1d..19e06d92 100644 --- a/crates/rake/src/control/web.rs +++ b/crates/rake/src/control/web.rs @@ -240,7 +240,10 @@ impl WebBridge { }; if let Err(error) = session.await { - crate::warn!(%error, "Development bridge disconnected; reconnecting"); + crate::warn!( + error_type = std::any::type_name_of_val(&error), + "Development bridge disconnected; reconnecting" + ); } crate::http::sleep(Duration::from_secs(1)).await; diff --git a/crates/rake/src/crash.rs b/crates/rake/src/crash.rs index 7c4c473c..a4c12c4d 100644 --- a/crates/rake/src/crash.rs +++ b/crates/rake/src/crash.rs @@ -164,6 +164,9 @@ impl CrashConfig { #[derive(Clone, Debug, Serialize, Deserialize)] #[non_exhaustive] pub struct CrashRecord { + /// Native application log path, when automatic file output is configured. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub log_path: Option, /// JSON schema version; currently 1. pub schema_version: u32, /// Stable opaque identity; sinks can use it to deduplicate retries. diff --git a/crates/rake/src/crash/native.rs b/crates/rake/src/crash/native.rs index a7b5cff8..86c555cb 100644 --- a/crates/rake/src/crash/native.rs +++ b/crates/rake/src/crash/native.rs @@ -255,6 +255,7 @@ impl CrashReporter { let location_truncated = location.as_ref().is_some_and(|text| text.len() > 256); CrashRecord { + log_path: crate::logging::path(), schema_version: 1, id: format!( "{:032}-{:010}-{:020}", diff --git a/crates/rake/src/crash/record.rs b/crates/rake/src/crash/record.rs index f2125834..36195288 100644 --- a/crates/rake/src/crash/record.rs +++ b/crates/rake/src/crash/record.rs @@ -98,6 +98,8 @@ pub(super) fn encode(record: &mut CrashRecord, limit: usize) -> io::Result {} @@ -59,7 +62,10 @@ impl CrashReports { wasm_bindgen_futures::spawn_local(async move { if let Err(error) = reporter.deliver(sink).await { // Web errors carry only fixed, privacy-safe category messages. - tracing::warn!(%error, "crash delivery failed; waiting record retained"); + tracing::warn!( + %error, + "crash delivery failed; waiting record retained" + ); } }); } diff --git a/crates/rake/src/crash/web.rs b/crates/rake/src/crash/web.rs index cc4d675c..86125051 100644 --- a/crates/rake/src/crash/web.rs +++ b/crates/rake/src/crash/web.rs @@ -91,6 +91,7 @@ impl CrashReporter { let (message, truncated) = panic_message(info.payload(), reporter.config.include_panic_message); let mut record = CrashRecord { + log_path: crate::logging::path(), schema_version: 1, id, timestamp_ms, diff --git a/crates/rake/src/lib.rs b/crates/rake/src/lib.rs index 2c2926be..92bd91f6 100644 --- a/crates/rake/src/lib.rs +++ b/crates/rake/src/lib.rs @@ -59,6 +59,7 @@ macro_rules! early_startup { pub mod control; pub mod crash; +pub mod logging; #[cfg(all(feature = "devtools-memory", unix))] pub mod memory; diff --git a/crates/rake/src/logging.rs b/crates/rake/src/logging.rs new file mode 100644 index 00000000..4b68fb9b --- /dev/null +++ b/crates/rake/src/logging.rs @@ -0,0 +1,348 @@ +//! Bounded private application logs, written only by the diagnostics worker. + +#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] +use std::path::PathBuf; +#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] +use std::sync::OnceLock; + +#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] +static PATH: OnceLock = OnceLock::new(); + +/// Configuration for automatic application logging. +#[derive(Clone, Debug, Default)] +#[must_use] +pub struct LogConfig { + /// Default severity; a valid `RAKE_LOG` environment value takes precedence. + /// If absent, the application's `log-level` preference is used, then INFO. + pub level: Option, +} + +#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] +pub(crate) fn path() -> Option { + PATH.get().map(|path| path.to_string_lossy().into_owned()) +} + +#[cfg(all(not(target_family = "wasm"), any(feature = "gpui", test)))] +mod native { + use super::PATH; + use crate::storage::file::{check_directory, check_file, private_options}; + use std::fs; + use std::io::{self, Write}; + use std::path::{Path, PathBuf}; + + // Four files of at most 1 MiB: a hard 4 MiB per-application budget. + const FILE_BYTES: u64 = 1024 * 1024; + const ROTATIONS: usize = 3; + + #[cfg(feature = "gpui")] + pub(super) fn directory(id: &str) -> Option { + if id.is_empty() + || id.len() > 128 + || matches!(id, "." | "..") + || !id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) + { + return None; + } + + #[cfg(target_os = "macos")] + let root = std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Library/Logs")); + + #[cfg(target_os = "windows")] + let root = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let root = std::env::var_os("XDG_STATE_HOME") + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + .or_else(|| { + std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local/state")) + }); + + root.filter(|root| root.is_absolute()) + .map(|root| root.join(id).join("logs")) + } + + struct LogWriter { + directory: PathBuf, + _lock: fs::File, + pending: Vec, + truncated: bool, + } + + impl LogWriter { + fn open(directory: PathBuf) -> io::Result { + let mut builder = fs::DirBuilder::new(); + + builder.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + + builder.create(&directory)?; + check_directory(&directory)?; + let lock = private_options() + .write(true) + .create(true) + .truncate(false) + .open(directory.join("writer.lock"))?; + + check_file(&lock)?; + lock.try_lock().map_err(io::Error::other)?; + + // Validate every managed file before any rotation or truncation. + for index in 0..=ROTATIONS { + let path = file_path(&directory, index); + + if path.try_exists()? { + let file = private_options().read(true).open(&path)?; + + check_file(&file)?; + + if file.metadata()?.len() > FILE_BYTES { + return Err(io::Error::other("oversized application log")); + } + } + } + + let file = private_options() + .append(true) + .create(true) + .open(file_path(&directory, 0))?; + + check_file(&file)?; + + Ok(Self { + directory, + _lock: lock, + pending: Vec::new(), + truncated: false, + }) + } + + fn line(&self, bytes: &[u8]) -> io::Result<()> { + check_directory(&self.directory)?; + let path = file_path(&self.directory, 0); + let mut file = private_options().append(true).create(true).open(&path)?; + + check_file(&file)?; + + if file.metadata()?.len().saturating_add(bytes.len() as u64) > FILE_BYTES { + drop(file); + + for index in (1..=ROTATIONS).rev() { + let old = file_path(&self.directory, index); + + match fs::remove_file(&old) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + + let previous = file_path(&self.directory, index - 1); + + match fs::rename(previous, old) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + + file = private_options().append(true).create_new(true).open(path)?; + } + + file.write_all(bytes) + } + } + + impl Drop for LogWriter { + fn drop(&mut self) { + // Explicit unlock also releases a descriptor inherited across fork. + let _ = self._lock.unlock(); + } + } + + fn file_path(directory: &Path, index: usize) -> PathBuf { + directory.join(if index == 0 { + "app.log".into() + } else { + format!("app.log.{index}") + }) + } + + impl Write for LogWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + for &byte in bytes { + // Reserve the last byte for framing even if a record is oversized. + if byte == b'\n' { + if self.truncated { + let marker = "…[truncated]".as_bytes(); + let end = crate::diagnostics::MAX_LOG_RECORD_BYTES - 1 - marker.len(); + + let end = std::str::from_utf8(&self.pending[..end]) + .map_or_else(|error| error.valid_up_to(), |_| end); + + self.pending.truncate(end); + self.pending.extend_from_slice(marker); + } + + self.pending.push(byte); + let _ = self.line(&self.pending); + + self.pending.clear(); + self.truncated = false; + } else if self.pending.len() < crate::diagnostics::MAX_LOG_RECORD_BYTES - 1 { + self.pending.push(byte); + } else { + self.truncated = true; + } + } + + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + pub(super) fn writer(directory: PathBuf) -> Box { + match LogWriter::open(directory) { + Ok(writer) => { + let _ = PATH.set(writer.directory.join("app.log")); + + Box::new(writer) + } + Err(_) => Box::new(io::sink()), + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn file_contains_same_redacted_message_and_target_as_ctl() { + use tracing_subscriber::prelude::*; + + let collector = crate::diagnostics::Collector::default(); + + let subscriber = tracing_subscriber::registry().with(collector.layer()); + + tracing::subscriber::with_default(subscriber, || { + crate::info!(target: "example::worker", api_key = "sensitive-value", detail = "a\nb", "saved application document"); + }); + + let snapshot = collector.logs_after(0); + let temporary = tempfile::tempdir().expect("temporary logs"); + let directory = temporary.path().join("logs"); + let mut writer = LogWriter::open(directory.clone()).expect("writer"); + + writeln!(writer, "{}", snapshot.records[0].line).expect("write"); + + let content = fs::read_to_string(file_path(&directory, 0)).expect("log file"); + + assert_eq!(content.trim_end(), snapshot.records[0].line); + assert!( + content.contains("example::worker") + && content.contains("saved application document") + ); + assert!(content.contains("api_key=[redacted]")); + assert!(!content.contains("sensitive-value")); + assert_eq!(content.lines().count(), 1); + } + + #[test] + fn oversized_lines_are_utf8_safe_marked_and_bounded() { + let temporary = tempfile::tempdir().expect("temporary logs"); + let directory = temporary.path().join("logs"); + let mut writer = LogWriter::open(directory.clone()).expect("writer"); + + writeln!(writer, "{}", "🦀".repeat(4096)).expect("write"); + + let content = fs::read_to_string(file_path(&directory, 0)).expect("valid UTF-8 log"); + + assert!(content.len() <= crate::diagnostics::MAX_LOG_RECORD_BYTES); + assert!(content.ends_with("…[truncated]\n")); + assert_eq!(content.lines().count(), 1); + } + + #[test] + fn rotation_bounds_and_exclusive_writer() { + let temporary = tempfile::tempdir().expect("temporary logs"); + let directory = temporary.path().join("logs"); + let mut writer = LogWriter::open(directory.clone()).expect("private writer"); + + assert!(LogWriter::open(directory.clone()).is_err()); + + let line = vec![b'x'; 256]; + + for _ in 0..(FILE_BYTES as usize * 5 / line.len()) { + writer.line(&line).expect("rotate"); + } + + writer.write_all(b"INFO event\n").expect("write"); + let sizes: Vec<_> = (0..=ROTATIONS) + .map(|index| { + fs::metadata(file_path(&directory, index)) + .expect("retained log") + .len() + }) + .collect(); + + assert!(sizes.iter().all(|size| *size <= FILE_BYTES)); + assert!(sizes.iter().sum::() <= FILE_BYTES * 4); + assert!( + fs::read_to_string(file_path(&directory, 0)) + .expect("tail") + .ends_with("INFO event\n") + ); + } + + #[test] + fn failing_directory_is_a_sink() { + let temporary = tempfile::tempdir().expect("temporary logs"); + let file = temporary.path().join("file"); + + fs::write(&file, b"occupied").expect("fixture"); + writer(file) + .write_all(b"INFO event\n") + .expect("failure is harmless"); + + let directory = temporary.path().join("logs"); + let mut writer = LogWriter::open(directory.clone()).expect("writer"); + + fs::remove_file(directory.join("app.log")).expect("remove empty log"); + fs::create_dir(directory.join("app.log")).expect("obstruct log file"); + writer + .write_all(b"INFO event\n") + .expect("write failure is harmless"); + } + } +} + +#[cfg(feature = "gpui")] +pub(crate) fn configure( + mut diagnostics: crate::diagnostics::DiagnosticsConfig, + id: &str, + config: LogConfig, +) -> crate::diagnostics::DiagnosticsConfig { + if let Some(level) = config.level.and_then(|level| level.parse().ok()) { + diagnostics = diagnostics.log_level(level); + } + + #[cfg(not(target_family = "wasm"))] + if !cfg!(debug_assertions) + && let Some(directory) = native::directory(id) + { + diagnostics = diagnostics.log_writer(move || native::writer(directory.clone())); + } + + #[cfg(target_family = "wasm")] + let _ = id; + + diagnostics +} diff --git a/crates/rake/src/menus.rs b/crates/rake/src/menus.rs index 6462f764..7509a256 100644 --- a/crates/rake/src/menus.rs +++ b/crates/rake/src/menus.rs @@ -317,7 +317,7 @@ pub(crate) fn install( let item = MenuItem::command(action.id.clone(), action.arguments.clone()); if let Err(error) = item.run(&client) { - tracing::error!(%error, command = %action.id, "menu command rejected"); + tracing::error!(error_type = std::any::type_name_of_val(&error), command = %action.id, "menu command rejected"); } }); cx.on_action(|action: &Standard, cx| match action.role { @@ -347,7 +347,10 @@ pub(crate) fn install( state_changed = commands.listen(); cx.update(|cx| { if let Err(error) = refresh(&menus, &commands, cx) { - tracing::error!(%error, "menu refresh rejected"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "menu refresh rejected" + ); } }); } diff --git a/crates/rake/src/router/navigation_view.rs b/crates/rake/src/router/navigation_view.rs index 5a382dd6..4b640c02 100644 --- a/crates/rake/src/router/navigation_view.rs +++ b/crates/rake/src/router/navigation_view.rs @@ -160,7 +160,10 @@ impl RenderOnce for NavigationBoundary { if let Ok(router) = action.runtime() && let Err(error) = router.retry_navigation(&retry) { - crate::warn!(%error, "navigation retry was rejected"); + crate::warn!( + error_type = std::any::type_name_of_val(&error), + "navigation retry was rejected" + ); } })); } diff --git a/crates/rake/src/router/runtime.rs b/crates/rake/src/router/runtime.rs index b75701b2..eea43a97 100644 --- a/crates/rake/src/router/runtime.rs +++ b/crates/rake/src/router/runtime.rs @@ -1228,6 +1228,10 @@ impl Router { } } + pub(crate) fn logs(&self, after: u64) -> crate::diagnostics::LogSnapshot { + self.0.collector.logs_after(after) + } + pub(crate) fn diagnostics( &self, after: u64, diff --git a/crates/rake/src/router/runtime/quit.rs b/crates/rake/src/router/runtime/quit.rs index 2c6508e7..e5e0a40f 100644 --- a/crates/rake/src/router/runtime/quit.rs +++ b/crates/rake/src/router/runtime/quit.rs @@ -270,7 +270,10 @@ impl Router { // The runtime owns this handoff. Disposing a routed page must // not cancel the final reload along with its observing view. if let Err(error) = Router(core.clone()).reload_page() { - tracing::error!(%error, "approved browser reload failed; reload manually"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "approved browser reload failed; reload manually" + ); } } } @@ -496,7 +499,10 @@ impl Router { if self.0.native_quit.borrow().is_none() { match rake_updates::NativeQuitBridge::new() { Ok(bridge) => *self.0.native_quit.borrow_mut() = Some(Rc::new(bridge)), - Err(error) => tracing::error!(%error,"native quit guard could not be installed"), + Err(error) => tracing::error!( + error_type = std::any::type_name_of_val(&error), + "native quit guard could not be installed" + ), } } diff --git a/crates/rake/src/router/runtime/tests.rs b/crates/rake/src/router/runtime/tests.rs index 11a03485..d12a656b 100644 --- a/crates/rake/src/router/runtime/tests.rs +++ b/crates/rake/src/router/runtime/tests.rs @@ -1333,3 +1333,46 @@ fn mount_registration_and_failed_mounts_follow_committed_entry_lifetimes() { assert_eq!(export.origin.entry_id, Some(opened.entry_id)); assert_eq!(export.origin.tab_id, Some(opened.tab_id)); } + +#[test] +fn log_queries_scrub_content_and_advance_the_cursor() { + use crate::control::{Message, PROTOCOL_VERSION, Query, Reply, Request}; + + let router = Router::::new(RouterConfig::default()); + + use tracing_subscriber::prelude::*; + let subscriber = tracing_subscriber::registry().with(router.0.collector.layer()); + + tracing::subscriber::with_default(subscriber, || { + crate::warn!(target: "example::worker", token = "secret", "application message"); + }); + + let query = |after| { + router + .client() + .request(Request { + protocol: PROTOCOL_VERSION, + runtime_id: router.runtime_id(), + key: None, + message: Message::Query(Query::Logs { after }), + }) + .expect("log query") + }; + + let Reply::Logs(snapshot) = query(0) else { + panic!("expected log reply") + }; + + assert_eq!(snapshot.records.len(), 1); + assert_eq!(snapshot.dropped, 0); + let records = snapshot.records; + let json = serde_json::to_string(&records).expect("log JSON"); + + assert!(!json.contains("secret")); + assert!(records[0].line.contains("WARN example::worker")); + assert!(records[0].line.contains("application message")); + assert!(records[0].line.contains("token=[redacted]")); + assert!( + matches!(query(records[0].sequence), Reply::Logs(snapshot) if snapshot.records.is_empty()) + ); +} diff --git a/crates/rake/src/router/runtime/updates.rs b/crates/rake/src/router/runtime/updates.rs index a1421566..f1587fac 100644 --- a/crates/rake/src/router/runtime/updates.rs +++ b/crates/rake/src/router/runtime/updates.rs @@ -114,7 +114,10 @@ impl Router { && matches!(updates.state(), UpdateState::ReadyToRestart(_)) && let Err(error) = self.restart_for_update(QuitOptions::default()) { - tracing::error!(%error, "native update restart was not admitted"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "native update restart was not admitted" + ); } if self.0.update_exit.get() == rake_updates::RestartDisposition::ProviderHandlesExit diff --git a/crates/rake/src/router/view.rs b/crates/rake/src/router/view.rs index 4fbd00b8..90f56339 100644 --- a/crates/rake/src/router/view.rs +++ b/crates/rake/src/router/view.rs @@ -683,7 +683,10 @@ impl Workspace { #[cfg(all(feature = "updates-sparkle", target_os = "macos"))] if let Err(error) = router.install_sparkle() { - tracing::error!(%error,"native updater could not start"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "native updater could not start" + ); } router.client().set_commands(commands); @@ -761,7 +764,10 @@ impl Workspace { } if let Err(error) = driven.run().await { - crate::error!(%error, "Router driver stopped"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "Router driver stopped" + ); } }; @@ -769,56 +775,73 @@ impl Workspace { let mut revision = u64::MAX; loop { - #[cfg(all(feature="updates",not(target_family="wasm")))] - let changed=Box::pin(observed.changed_with_updates(revision)); + #[cfg(all(feature = "updates", not(target_family = "wasm")))] + let changed = Box::pin(observed.changed_with_updates(revision)); #[cfg(all( - not(feature="updates"), - feature="native-lifecycle", - target_os="macos" + not(feature = "updates"), + feature = "native-lifecycle", + target_os = "macos" ))] - let changed=Box::pin(observed.changed_with_native_quit(revision)); + let changed = Box::pin(observed.changed_with_native_quit(revision)); #[cfg(not(any( - all(feature="updates",not(target_family="wasm")), + all(feature = "updates", not(target_family = "wasm")), all( - not(feature="updates"), - feature="native-lifecycle", - target_os="macos" + not(feature = "updates"), + feature = "native-lifecycle", + target_os = "macos" ) )))] - let changed=Box::pin(observed.changed(revision)); + let changed = Box::pin(observed.changed(revision)); - #[cfg(feature="devtools")] + #[cfg(feature = "devtools")] { - let inspection=observed.client().inspection().listen(); + let inspection = observed.client().inspection().listen(); - if let futures::future::Either::Left((next,_))=futures::future::select(changed,Box::pin(inspection)).await {revision=next;} + if let futures::future::Either::Left((next, _)) = + futures::future::select(changed, Box::pin(inspection)).await + { + revision = next; + } + } + #[cfg(not(feature = "devtools"))] + { + revision = changed.await; } - #[cfg(not(feature="devtools"))] - {revision=changed.await;} #[cfg(not(target_family = "wasm"))] if observed.quit_status().phase == crate::quit::QuitPhase::Ready { closing.responses_idle().await; - #[cfg(all(feature="native-lifecycle",target_os="macos"))] + #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] observed.prepare_native_exit(true); - #[cfg(feature="updates")] + #[cfg(feature = "updates")] match observed.complete_update_restart() { - Ok(rake_updates::RestartDisposition::ProviderHandlesExit)=>continue, - Ok(rake_updates::RestartDisposition::ExitHost)=>{}, - Err(error)=>{ - #[cfg(all(feature="native-lifecycle",target_os="macos"))] - {observed.reply_native_quit(false);observed.prepare_native_exit(true);} - tracing::error!(%error,"update handoff failed; manual restart required"); - let _=_view.update(cx,|_,cx|cx.notify()); + Ok(rake_updates::RestartDisposition::ProviderHandlesExit) => { + continue; + } + Ok(rake_updates::RestartDisposition::ExitHost) => {} + Err(error) => { + #[cfg(all( + feature = "native-lifecycle", + target_os = "macos" + ))] + { + observed.reply_native_quit(false); + observed.prepare_native_exit(true); + } + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "update handoff failed; manual restart required" + ); + let _ = _view.update(cx, |_, cx| cx.notify()); break; } } - #[cfg(all(feature="native-lifecycle",target_os="macos"))] + #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] observed.reply_native_quit(true); cx.update(|cx| cx.quit()); @@ -1182,7 +1205,10 @@ impl Render for Workspace { }; if let Err(error) = result { - tracing::error!(%error, "update action failed"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "update action failed" + ); } }) }, diff --git a/crates/rake/src/surface.rs b/crates/rake/src/surface.rs index ad3f88a8..cae126a9 100644 --- a/crates/rake/src/surface.rs +++ b/crates/rake/src/surface.rs @@ -340,7 +340,10 @@ impl Element for GpuSurfaceElement { closed: false, }; if let Err(error) = inner.host.place(bounds, clip, state) { - tracing::error!(%error, "GPU surface placement failed"); + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "GPU surface placement failed" + ); inner.hide(); return; } diff --git a/crates/rake/src/surface/native.rs b/crates/rake/src/surface/native.rs index cdd0c586..ce3ae1d0 100644 --- a/crates/rake/src/surface/native.rs +++ b/crates/rake/src/surface/native.rs @@ -106,7 +106,10 @@ impl Host { pub(super) fn hide(&self) { if let Err(error) = self.set_visible(false) { - tracing::debug!(%error, "GPU surface could not be hidden"); + tracing::debug!( + error_type = std::any::type_name_of_val(&error), + "GPU surface could not be hidden" + ); } } diff --git a/crates/rake/src/tray.rs b/crates/rake/src/tray.rs index da79c1e6..ff28c741 100644 --- a/crates/rake/src/tray.rs +++ b/crates/rake/src/tray.rs @@ -82,7 +82,10 @@ pub(crate) fn command_handler( .and_then(|dispatch| dispatch(command_id.clone(), arguments.clone())); if let Err(error) = result { - crate::error!(%error, "tray command rejected"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "tray command rejected" + ); } })) } @@ -123,7 +126,10 @@ impl gpui::Global for Owner {} pub(crate) fn stop(cx: &mut gpui::App) { #[cfg(target_os = "macos")] if let Err(error) = rake_updates::stop_application_run_loop() { - crate::error!(%error, "native tray startup could not stop the host loop"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "native tray startup could not stop the host loop" + ); } #[cfg(not(target_os = "macos"))] @@ -174,7 +180,10 @@ fn report_unregistered_failure( handlers: &mut [Handler], cx: &mut gpui::App, ) { - crate::error!(tray = %id, %error, "optional tray could not register"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "optional tray could not register" + ); let event = Event { id, generation: 0, @@ -277,7 +286,10 @@ fn install_with( let operations = cx.spawn(async move |_| { if let Err(error) = work.await { - crate::error!(%error, "tray operation driver stopped"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "tray operation driver stopped" + ); } }); @@ -322,7 +334,10 @@ fn install_with( }); if let Err(error) = shutdown.await { - crate::error!(%error, "tray startup rollback failed"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "tray startup rollback failed" + ); } cx.update(stop_host); @@ -340,7 +355,10 @@ fn install_with( async move { if let Err(error) = shutdown.await { - crate::error!(%error, "native tray shutdown failed"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "native tray shutdown failed" + ); } } }); @@ -358,7 +376,9 @@ fn install_with( popup::removed(&event.id, event.generation, cx); cx.global_mut::().animations.remove(&event.id); - if matches!(event.kind, EventKind::Removed) { cx.global_mut::().removal_quits.remove(&event.id); } + if matches!(event.kind, EventKind::Removed) { + cx.global_mut::().removal_quits.remove(&event.id); + } } if let Ok(handle) = collection.get(&event.id) @@ -379,18 +399,26 @@ fn install_with( let task = cx.spawn(async move |_| { if let Err(error) = quit_from_removal(quit, move || item.show()).await { - crate::error!(%error, "removed tray item could not be restored after declined quit"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "removed tray item could not be restored after declined quit" + ); } }); - cx.global_mut::().removal_quits.insert(event.id.clone(), task); + cx.global_mut::() + .removal_quits + .insert(event.id.clone(), task); } if matches!(event.kind, EventKind::Activate) && spec.primary_interaction() == Interaction::Popup && let Err(error) = toggle_popup(&event.id, cx) { - crate::error!(%error, "tray popup could not open"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "tray popup could not open" + ); } let menu_gesture = matches!(event.kind, EventKind::ContextMenu) @@ -403,20 +431,23 @@ fn install_with( == Support::Supported && let Err(error) = handle.show_menu() { - crate::error!(%error, "tray menu could not open"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "tray menu could not open" + ); } } if matches!(event.kind, EventKind::HostChanged(false)) { - crate::warn!(tray = %event.id, "tray host unavailable; registration is waiting"); + crate::warn!("tray host unavailable; registration is waiting"); } - if let EventKind::Diagnostic(message) = &event.kind { - crate::warn!(tray = %event.id, %message, "native tray diagnostic"); + if let EventKind::Diagnostic(_) = &event.kind { + crate::warn!("native tray diagnostic"); } - if let EventKind::OperationFailed(message) = &event.kind { - crate::error!(tray = %event.id, %message, "native tray operation failed"); + if let EventKind::OperationFailed(_) = &event.kind { + crate::error!("native tray operation failed"); } if matches!(event.kind, EventKind::Overflow) { @@ -508,7 +539,10 @@ pub fn animate(id: &str, animation: Animation, cx: &mut gpui::App) -> Result<(), match handle.set_icon(frames[frame].clone()).await { Ok(applied) => revision = applied.revision, Err(error) => { - crate::error!(%error, "tray animation stopped"); + crate::error!( + error_type = std::any::type_name_of_val(&error), + "tray animation stopped" + ); break; } } diff --git a/crates/rake/src/window_state.rs b/crates/rake/src/window_state.rs index e3d9730a..81a09110 100644 --- a/crates/rake/src/window_state.rs +++ b/crates/rake/src/window_state.rs @@ -150,7 +150,10 @@ impl WindowState { self.load_locked().await }) { - crate::warn!(%error, "window placement could not be loaded; using defaults"); + crate::warn!( + error_type = std::any::type_name_of_val(&error), + "window placement could not be loaded; using defaults" + ); } } @@ -159,7 +162,10 @@ impl WindowState { let _write = self.inner.writes.lock().await; if let Err(error) = self.save_locked().await { - crate::warn!(%error, "window placement could not be saved"); + crate::warn!( + error_type = std::any::type_name_of_val(&error), + "window placement could not be saved" + ); } } } diff --git a/crates/rake/tests/local_control.rs b/crates/rake/tests/local_control.rs index 6a2caed7..7f135551 100644 --- a/crates/rake/tests/local_control.rs +++ b/crates/rake/tests/local_control.rs @@ -55,6 +55,10 @@ fn native_endpoint_round_trip_bounds_and_discovery_lifetime() { let reply = rake_client::query(&instance, Query::Info {}, Duration::from_secs(3)).unwrap(); assert!(matches!(reply, Reply::Info(_))); + let reply = rake_client::query(&instance, Query::Logs { after: 0 }, Duration::from_secs(3)) + .unwrap(); + + assert!(matches!(reply, Reply::Logs(_))); let rake_client::Endpoint::Local { path } = &instance.endpoint else { panic!("expected local endpoint") diff --git a/docs/logging.md b/docs/logging.md new file mode 100644 index 00000000..024e3b4e --- /dev/null +++ b/docs/logging.md @@ -0,0 +1,123 @@ +# Application logging + +`App` installs a default tracing subscriber. Use `rake::info!`, `warn!`, +`error!`, `debug!` and `trace!` as usual. Development builds write to stderr; +packaged (release) builds write private rotating files. Browser builds write to +the console and never use a native file or worker thread. + +The existing `background` example emits a startup event. Build it in release mode +(`cargo run -p rake-app --release --example background`) to exercise file logging +on a native desktop; its development build emits to stderr. + +## Paths and limits + +For application ID `ID`, the current log is: + +| Platform | Path | +| --- | --- | +| macOS | `~/Library/Logs/ID/logs/app.log` | +| Windows | `%LOCALAPPDATA%\ID\logs\app.log` | +| Linux | `$XDG_STATE_HOME/ID/logs/app.log`, default `~/.local/state/ID/logs/app.log` | + +Roots must be absolute. Files are private (0600) and the application log directory +is private (0700) on Unix. Unix also rejects existing symlink files and nonprivate +files/directories using the same checks as crash storage. Keep the parent directory +trusted. Windows uses the user's inherited profile ACLs. + +Each file is at most 1 MiB. Rotation retains `app.log.1` through `app.log.3`, for +a total budget of 4 MiB per application ID, plus an empty writer lock. A second +process using the same directory does not write while the first owns the lock. +No unrelated files are deleted. Existing oversized or unsafe logs disable output +for that launch rather than modifying untrusted files. + +All file creation, locking, rotation and writes run on the existing diagnostics +worker. Producers use a queue of 1024 bounded formatted lines and never wait for +a disk write. A full queue drops output; `Snapshot::output_dropped` counts queue +loss. Missing roots, denied permissions, full disks and write failures discard +file output and do not stop the application. This is best-effort troubleshooting, +not an audit trail; queued lines can be lost on exit or panic. + +## Configuration + +The severity is selected in this order: a valid `RAKE_LOG` environment value, +`App::logging(LogConfig { level: Some(...), ..Default::default() })`, the +application-ID preference `log-level`, then INFO. Values are `off`, `error`, +`warn`, `info`, `debug` or `trace`, case insensitive. Invalid values fall back. +Preferences are sampled once at startup; changing them takes effect on relaunch. + +```rust,ignore +let app = rake::App::new("example.app").logging(rake::logging::LogConfig { + level: Some("warn".into()), +}); +``` + +`App::without_logging()` leaves subscriber ownership to the host. The existing +`DiagnosticsConfig::subscriber(SubscriberMode::Host)` also supports replacement; +attach the shared collector layer to a custom subscriber if ctl diagnostics are +needed. Custom native output can use `DiagnosticsConfig::log_writer`; its factory +runs on the output worker. A host is responsible for its own output privacy and +retention. Logging and crash recording can be disabled independently. + +## Read and tail a running app + +Use the existing private ctl endpoint and runtime selection options: + +```sh +rake ctl logs +rake ctl logs list --after 42 +rake ctl logs --follow +# Equivalent: rake ctl logs follow +``` + +These commands query the running app through ctl, without opening arbitrary paths. +Replies are JSON snapshots with cumulative dropped/output-dropped counts and +records with a log sequence and a `line` containing the same UTC timestamp, +level, target, message and redacted fields sent to the file writer. Follow advances the sequence cursor and suppresses empty replies, using the +existing ctl timeout. The retained tail is at most 128 records, also limited by +the configured collector capacity and a 256 KiB encoded retention budget (so +escaped JSON fits the ctl transport frame). Contention or evictions may leave gaps; this +is not a replay of older rotated files. `logs list` uses the same privacy policy. +Development `requests list` and `traces export` remain diagnostic tools and may +contain application-supplied fields. + +## Privacy and crash reports + +File logs and ctl logs retain what the application chooses to log. A line contains +an RFC 3339 UTC wall-clock timestamp, severity, target, message, and event fields +plus inherited span fields. For example: + +```text +2026-11-15T12:30:00Z INFO example::worker "save complete" count=3 api_key=[redacted] +``` + +Field names are matched using case-insensitive substrings: `password`, `passwd`, +`secret`, `token`, `authorization`, `cookie`, `api_key`, `apikey`, `credential`, +`private_key`, and `session`. Matching values become `[redacted]`. Newlines and +carriage returns in values are escaped, so one event always occupies one line. +Each record is at most 4 KiB of UTF-8 including its newline. Oversized records end +in `…[truncated]`; truncation preserves UTF-8. + +Rake's own call sites log fixed operation categories, static error types, bounded +identifiers and structural status. They do not format error payloads, document or +clipboard contents, notification bodies, URL query strings, or local file paths. +The log directory and optional crash-record `log_path` necessarily identify a +local filesystem path. No artifacts are uploaded automatically. + +Apps must avoid logging secrets in messages, targets, field names, or values under +unrecognized keys. Key redaction is a heuristic, not content scanning: it cannot +recognize credentials inside an arbitrary message, URL, nested debug object, or +free-form error. Apps must sanitize home paths, URL queries, clipboard/text data, +and notification bodies before logging them. Review logs before sharing them. +Development stderr and browser console retain their existing format and fields; +key redaction applies to file and ctl output. Host-owned subscribers, output +writers and log bridges require their own privacy policy. + +Crash diagnostics remain structural only; they do not inherit the richer log +content. The ctl ring and file queue are independently best-effort: contention, +evictions, queue overflow, disk failures or process exit may leave different +subsets retained or persisted, but a retained `line` is formatted identically. + +Native crash records optionally include `log_path` when the file worker opened +successfully. That path can contain a local account name. Log contents are never +copied into crash records or uploaded automatically. Sharing either artifact +requires the application's own consent and delivery policy. diff --git a/docs/runtime-control.md b/docs/runtime-control.md index 5ac43e1b..81792824 100644 --- a/docs/runtime-control.md +++ b/docs/runtime-control.md @@ -210,9 +210,11 @@ Handlers don't hold a router scheduling lane, so a handler can await navigation State is coalesced and intermediate mutations aren't replayed. A skipped revision, stale epoch or other runtime returns `Gap` plus a fresh snapshot, and an unchanged poll contains no snapshot. Consumers replace their state on Snapshot, Changed or Gap. Tracing loss never defines authoritative routing or operation state. -`logs follow`, `requests list`, `traces export` and raw Diagnostics queries expose -collector sequence numbers and cumulative dropped/output-dropped counts. They are -best-effort diagnostics and have separate retention from state events. +`rake ctl logs` and `logs follow` expose a redacted formatted log tail with +log sequences and cumulative dropped/output-dropped counts; see +[Application logging](logging.md). `requests list`, `traces export` and raw +Diagnostics queries expose full development records and the same loss counters. +These are best-effort diagnostics with separate retention from state events. | Limit | Value | | --- | --- | diff --git a/vendor/gpui-base/src/input/base/state.rs b/vendor/gpui-base/src/input/base/state.rs index 3d0fdeac..eabd6fda 100644 --- a/vendor/gpui-base/src/input/base/state.rs +++ b/vendor/gpui-base/src/input/base/state.rs @@ -3254,7 +3254,10 @@ impl InputBaseState { .ok(); } Ok(None) => {} - Err(error) => tracing::warn!("failed to read the clipboard for paste: {error}"), + Err(error) => tracing::warn!( + error_type = std::any::type_name_of_val(&error), + "failed to read the clipboard for paste" + ), }) .detach(); } diff --git a/vendor/gpui-base/src/text/format/markdown.rs b/vendor/gpui-base/src/text/format/markdown.rs index 7fa574dd..24012c1c 100644 --- a/vendor/gpui-base/src/text/format/markdown.rs +++ b/vendor/gpui-base/src/text/format/markdown.rs @@ -909,13 +909,16 @@ fn parse_paragraph( text = inline_text; } else { if cfg!(debug_assertions) { - tracing::warn!("unsupported inline html tag: {:#?}", val.value); + tracing::warn!("unsupported inline html tag"); } } } Err(err) => { if cfg!(debug_assertions) { - tracing::warn!("failed parsing html: {:#?}", err); + tracing::warn!( + error_type = std::any::type_name_of_val(&err), + "failed parsing html" + ); } text.push_str(&val.value); @@ -951,7 +954,7 @@ fn parse_paragraph( } _ => { if cfg!(debug_assertions) { - tracing::warn!("unsupported inline node: {:#?}", node); + tracing::warn!("unsupported inline node"); } } } @@ -1103,7 +1106,10 @@ fn ast_to_node(source: &str, value: mdast::Node, cx: &mut NodeContext) -> BlockN }, Err(err) => { if cfg!(debug_assertions) { - tracing::warn!("error parsing html: {:#?}", err); + tracing::warn!( + error_type = std::any::type_name_of_val(&err), + "error parsing html" + ); } BlockNode::Paragraph(Paragraph::new(val.value)) @@ -1182,7 +1188,7 @@ fn ast_to_node(source: &str, value: mdast::Node, cx: &mut NodeContext) -> BlockN }, _ => { if cfg!(debug_assertions) { - tracing::warn!("unsupported node: {:#?}", value); + tracing::warn!("unsupported node"); } BlockNode::Unknown } diff --git a/vendor/gpui-base/src/text/node.rs b/vendor/gpui-base/src/text/node.rs index c8a8c855..f78fa16f 100644 --- a/vendor/gpui-base/src/text/node.rs +++ b/vendor/gpui-base/src/text/node.rs @@ -4461,7 +4461,7 @@ impl BlockNode { BlockNode::Unknown { .. } | BlockNode::Definition { .. } => div().into_any_element(), _ => { if cfg!(debug_assertions) { - tracing::warn!("unknown implementation: {:?}", self); + tracing::warn!("unknown text node implementation"); } div().into_any_element() diff --git a/vendor/gpui-pre-web/src/dispatcher.rs b/vendor/gpui-pre-web/src/dispatcher.rs index f529d8e6..a78800c4 100644 --- a/vendor/gpui-pre-web/src/dispatcher.rs +++ b/vendor/gpui-pre-web/src/dispatcher.rs @@ -118,7 +118,10 @@ impl MainThreadMailbox { let result = match js_sys::Atomics::wait_async(&view, 0, 0) { Ok(result) => result, Err(error) => { - log::error!("Atomics.waitAsync failed: {error:?}"); + log::error!( + "Atomics.waitAsync failed: {}", + std::any::type_name_of_val(&error) + ); break; } }; @@ -245,7 +248,10 @@ impl PlatformDispatcher for WebDispatcher { }; if let Err(error) = result { - log::error!("dispatch: failed to send to background queue: {error:?}"); + log::error!( + "dispatch: failed to send to background queue: {}", + std::any::type_name_of_val(&error) + ); } } @@ -388,7 +394,10 @@ fn schedule_idle_runnable( None => window.request_idle_callback(callback.unchecked_ref()), }; if let Err(error) = result { - log::error!("requestIdleCallback failed: {error:?}"); + log::error!( + "requestIdleCallback failed: {}", + std::any::type_name_of_val(&error) + ); } } diff --git a/vendor/gpui-pre-web/src/events.rs b/vendor/gpui-pre-web/src/events.rs index c3f8cd8b..3219fd8a 100644 --- a/vendor/gpui-pre-web/src/events.rs +++ b/vendor/gpui-pre-web/src/events.rs @@ -534,7 +534,10 @@ impl WebWindowInner { .browser_window .set_timeout_with_callback(callback.unchecked_ref()) { - log::warn!("failed to defer web window activation: {error:?}"); + log::warn!( + "failed to defer web window activation: {}", + std::any::type_name_of_val(&error) + ); } } @@ -863,7 +866,9 @@ impl WebWindowInner { &old_units, &new_units, start as usize..end as usize, - this.ime_mirror.selection_start().map(|caret| caret as usize), + this.ime_mirror + .selection_start() + .map(|caret| caret as usize), ); let applied = this.with_input_handler(|handler| { @@ -1074,7 +1079,7 @@ impl WebWindowInner { Err(error) => { log::error!( "failed to read pasted image: {}", - crate::platform::js_error_message(&error) + std::any::type_name_of_val(&error) ); } } diff --git a/vendor/gpui-pre-web/src/http_client.rs b/vendor/gpui-pre-web/src/http_client.rs index 848c9df7..daf0852e 100644 --- a/vendor/gpui-pre-web/src/http_client.rs +++ b/vendor/gpui-pre-web/src/http_client.rs @@ -167,15 +167,12 @@ async fn fetch( (Some(name), Some(value)) => { builder = builder.header(name, value); } - (name, value) => { - log::warn!( - "skipping response header at index {index}: \ - name={name:?}, value={value:?}" - ); + (_, _) => { + log::warn!("skipping response header at index {index}: invalid header"); } }, - Err(entry) => { - log::warn!("skipping non-array header entry at index {index}: {entry:?}"); + Err(_) => { + log::warn!("skipping non-array header entry at index {index}"); } } } @@ -307,6 +304,9 @@ fn response_chunk(result: JsValue) -> io::Result>> { async fn cancel_reader(reader: &web_sys::ReadableStreamDefaultReader) { if let Err(error) = wasm_bindgen_futures::JsFuture::from(reader.cancel()).await { - log::debug!("failed to cancel response body reader: {error:?}"); + log::debug!( + "failed to cancel response body reader: {}", + std::any::type_name_of_val(&error) + ); } } diff --git a/vendor/gpui-pre-web/src/ime_mirror.rs b/vendor/gpui-pre-web/src/ime_mirror.rs index 5cb08b5a..950556c3 100644 --- a/vendor/gpui-pre-web/src/ime_mirror.rs +++ b/vendor/gpui-pre-web/src/ime_mirror.rs @@ -192,7 +192,10 @@ impl ImeMirror { let options = web_sys::FocusOptions::new(); options.set_prevent_scroll(true); if let Err(error) = element.focus_with_options(&options) { - log::warn!("Failed to focus IME mirror: {error:?}"); + log::warn!( + "Failed to focus IME mirror: {}", + std::any::type_name_of_val(&error) + ); } } @@ -221,7 +224,10 @@ impl ImeMirror { .element .set_attribute("inputmode", if enabled { "text" } else { "none" }) { - log::warn!("Failed to configure input mode: {error:?}"); + log::warn!( + "Failed to configure input mode: {}", + std::any::type_name_of_val(&error) + ); } } diff --git a/vendor/gpui-pre-web/src/platform.rs b/vendor/gpui-pre-web/src/platform.rs index b496aa4f..561807de 100644 --- a/vendor/gpui-pre-web/src/platform.rs +++ b/vendor/gpui-pre-web/src/platform.rs @@ -253,7 +253,8 @@ async fn initialize_graphics( let canvas: &web_sys::Element = webgpu_canvas.as_ref(); canvas.remove(); log::warn!( - "WebGPU initialization failed; falling back to WebGL2: {webgpu_error:#}" + "WebGPU initialization failed; falling back to WebGL2 ({})", + std::any::type_name_of_val(&webgpu_error) ); let webgl_canvas = @@ -344,7 +345,10 @@ impl Platform for WebPlatform { } Err(error) => { window_lifecycle.set(WebWindowLifecycle::Unavailable); - log::error!("Failed to initialize browser graphics: {error:#}"); + log::error!( + "Failed to initialize browser graphics: {}", + std::any::type_name_of_val(&error) + ); show_graphics_unavailable_message(&browser_window, &error); } } @@ -463,7 +467,10 @@ impl Platform for WebPlatform { fn open_url(&self, url: &str) { if let Err(error) = self.browser_window.open_with_url(url) { - log::warn!("Failed to open URL '{url}': {error:?}"); + log::warn!( + "Failed to open URL ({})", + std::any::type_name_of_val(&error) + ); } } @@ -777,11 +784,8 @@ pub(crate) fn js_error_message(error: &JsValue) -> String { .unwrap_or_else(|| "unknown browser error".to_string()) } -fn log_clipboard_entry_error(mime_type: &str, error: &JsValue) { - log::warn!( - "failed to read clipboard entry with type {mime_type}: {}", - js_error_message(error) - ); +fn log_clipboard_entry_error(_mime_type: &str, _error: &JsValue) { + log::warn!("failed to read clipboard entry"); } fn cursor_restore_listeners( @@ -841,6 +845,9 @@ fn set_body_cursor(browser_window: &web_sys::Window, css_cursor: &str) { && let Some(body) = document.body() && let Err(error) = body.style().set_property("cursor", css_cursor) { - log::warn!("Failed to set cursor style: {error:?}"); + log::warn!( + "Failed to set cursor style: {}", + std::any::type_name_of_val(&error) + ); } } diff --git a/vendor/gpui-pre-web/src/text_system.rs b/vendor/gpui-pre-web/src/text_system.rs index e8ce869a..91828dc7 100644 --- a/vendor/gpui-pre-web/src/text_system.rs +++ b/vendor/gpui-pre-web/src/text_system.rs @@ -233,7 +233,10 @@ impl WebTextSystem { })(); match replacement { Ok(replacement) => replacements.push(replacement), - Err(error) => log::warn!("Canvas font fallback failed: {error:#}"), + Err(error) => log::warn!( + "Canvas font fallback failed: {}", + std::any::type_name_of_val(&error) + ), } } if replacements.is_empty() { @@ -333,7 +336,10 @@ impl PlatformTextSystem for WebTextSystem { match self.register_glyph(font_id, text, color) { Ok(glyph_id) => Some(glyph_id), Err(error) => { - log::warn!("registering Canvas glyph failed: {error:#}"); + log::warn!( + "registering Canvas glyph failed: {}", + std::any::type_name_of_val(&error) + ); None } } diff --git a/vendor/gpui-pre-web/src/window.rs b/vendor/gpui-pre-web/src/window.rs index ddd90950..b9f68233 100644 --- a/vendor/gpui-pre-web/src/window.rs +++ b/vendor/gpui-pre-web/src/window.rs @@ -259,7 +259,10 @@ impl WebWindow { Some(observer) } Err(error) => { - log::warn!("Failed to observe safe area: {error:?}"); + log::warn!( + "Failed to observe safe area: {}", + std::any::type_name_of_val(&error) + ); None } }; @@ -406,7 +409,10 @@ impl WebWindowInner { { Ok(changed) => changed, Err(error) => { - log::warn!("Failed to update browser viewport: {error:#}"); + log::warn!( + "Failed to update browser viewport: {}", + std::any::type_name_of_val(&error) + ); false } } @@ -817,7 +823,10 @@ impl PlatformWindow for WebWindow { .browser_window .set_timeout_with_callback(callback.unchecked_ref()) { - log::warn!("failed to restore keyboard event receiver: {error:?}"); + log::warn!( + "failed to restore keyboard event receiver: {}", + std::any::type_name_of_val(&error) + ); } }