From 3c2e5708f03066571ae4ce78236ec3ba11872eea Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 21:01:44 +0000 Subject: [PATCH 01/10] docs: start application logging guide Co-Authored-By: Claude Opus 5.5 --- docs/logging.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 docs/logging.md diff --git a/docs/logging.md b/docs/logging.md new file mode 100644 index 0000000..adfafa2 --- /dev/null +++ b/docs/logging.md @@ -0,0 +1,4 @@ +# Application logging + +App logging uses Rake's tracing macros and bounded diagnostic output worker. +Implementation and configuration details are being added with issue #84. From 6855b2996cc300a5f59d0eee787e9cd319b3369c Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 21:11:55 +0000 Subject: [PATCH 02/10] feat: add bounded private application logs and ctl tail Co-Authored-By: Claude Opus 5.5 --- crates/rake-cli/src/terminal.rs | 52 ++++- crates/rake-diagnostics/src/lib.rs | 82 ++++++-- crates/rake-diagnostics/src/tests.rs | 83 +++++++- crates/rake-protocol/src/control.rs | 8 + crates/rake/examples/background.rs | 1 + crates/rake/src/application.rs | 45 ++++ crates/rake/src/control/mod.rs | 1 + crates/rake/src/crash.rs | 3 + crates/rake/src/crash/native.rs | 1 + crates/rake/src/crash/record.rs | 2 + crates/rake/src/crash/web.rs | 1 + crates/rake/src/lib.rs | 1 + crates/rake/src/logging.rs | 266 ++++++++++++++++++++++++ crates/rake/src/router/runtime.rs | 10 + crates/rake/src/router/runtime/tests.rs | 40 ++++ crates/rake/tests/local_control.rs | 3 + docs/logging.md | 93 ++++++++- 17 files changed, 671 insertions(+), 21 deletions(-) create mode 100644 crates/rake/src/logging.rs diff --git a/crates/rake-cli/src/terminal.rs b/crates/rake-cli/src/terminal.rs index 57c0fc6..01ad7ea 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(records)) => { + if let Some(record) = 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(records) if 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/src/lib.rs b/crates/rake-diagnostics/src/lib.rs index 1394939..2783dc1 100644 --- a/crates/rake-diagnostics/src/lib.rs +++ b/crates/rake-diagnostics/src/lib.rs @@ -711,12 +711,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 +751,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 contains structural metadata only, just like crash diagnostics. + #[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 @@ -758,8 +783,14 @@ 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(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 +810,8 @@ pub enum DiagnosticsError { } struct OutputLayer { + private: bool, + started: Instant, #[cfg(all(feature = "devtools", not(target_family = "wasm")))] mirror_marker: bool, #[cfg(not(target_family = "wasm"))] @@ -788,23 +821,32 @@ 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 private = 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 { + private, + started: Instant::now(), sender, collector, #[cfg(feature = "devtools")] @@ -815,9 +857,12 @@ impl OutputLayer { #[cfg(target_family = "wasm")] { - let _ = collector; + let _ = (collector, config); - Ok(Self {}) + Ok(Self { + private: false, + started: Instant::now(), + }) } } } @@ -826,13 +871,24 @@ 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 - ); + if !self.private { + event.record(&mut fields); + } + + let text = if self.private { + format!( + "{}us {} event", + self.started.elapsed().as_micros(), + event.metadata().level() + ) + } else { + format!( + "{} {} {:?}", + event.metadata().level(), + event.metadata().target(), + fields.0 + ) + }; #[cfg(all(feature = "devtools", not(target_family = "wasm")))] let text = if self.mirror_marker { diff --git a/crates/rake-diagnostics/src/tests.rs b/crates/rake-diagnostics/src/tests.rs index b56f303..d0cd82f 100644 --- a/crates/rake-diagnostics/src/tests.rs +++ b/crates/rake-diagnostics/src/tests.rs @@ -5,7 +5,7 @@ use tracing_subscriber::prelude::*; -use super::{Collector, OutputLayer}; +use super::{Collector, DiagnosticsConfig, Instant, OutputLayer, Registry}; #[test] fn a_full_output_queue_reports_loss_and_keeps_collecting() { @@ -15,6 +15,8 @@ fn a_full_output_queue_reports_loss_and_keeps_collecting() { let subscriber = tracing_subscriber::registry() .with(collector.layer()) .with(OutputLayer { + private: false, + started: Instant::now(), #[cfg(feature = "devtools")] mirror_marker: false, sender, @@ -80,3 +82,82 @@ fn crash_tail_keeps_only_bounded_structural_metadata() { .all(|item| item.level == "unknown" && item.kind == "unknown") ); } + +#[test] +fn private_output_is_bounded_concurrent_and_omits_payloads() { + 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(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.ends_with(" WARN event"))); + assert!(!output.contains("secret") && !output.contains("private user content")); + 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 { + private: true, + started: Instant::now(), + sender, + collector: collector.clone(), + #[cfg(feature = "devtools")] + mirror_marker: false, + }; + let subscriber = Registry::default().with(layer); + tracing::subscriber::with_default(subscriber, || tracing::info!("dropped")); + + assert_eq!(collector.snapshot().output_dropped, 1); +} diff --git a/crates/rake-protocol/src/control.rs b/crates/rake-protocol/src/control.rs index 83a47f2..2341f1b 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, }, + /// Privacy-safe application log metadata after a collector sequence. + Logs { + /// Exclusive collector 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), + /// Structural application log tail, with arbitrary text and fields omitted. + Logs(Vec), } /// Structured protocol errors; transport failures are reported separately as I/O errors. diff --git a/crates/rake/examples/background.rs b/crates/rake/examples/background.rs index e52f222..2441c6c 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 554a4e1..4fc5881 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,23 @@ impl App { self } + /// Configures automatic logging. `RAKE_LOG` overrides the level preference. + pub fn logging(mut self, config: crate::logging::LogConfig) -> Self { + self.logging = Some(config); + + 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 +1026,31 @@ impl App { return Err(AppError::MissingRoot); }; + if let Some(mut config) = self.logging.take() { + if config.level.is_none() { + if 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")] diff --git a/crates/rake/src/control/mod.rs b/crates/rake/src/control/mod.rs index 04781df..be326bc 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()), )), diff --git a/crates/rake/src/crash.rs b/crates/rake/src/crash.rs index 7c4c473..a4c12c4 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 a7b5cff..86c555c 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 f212583..3619528 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 = 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, +} + +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, + } + + 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")); + } + } + } + + Ok(Self { + directory, + _lock: lock, + pending: Vec::new(), + }) + } + + 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' { + self.pending.push(byte); + let _ = self.line(&self.pending); + self.pending.clear(); + } else if self.pending.len() < 255 { + self.pending.push(byte); + } + } + + 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 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::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/router/runtime.rs b/crates/rake/src/router/runtime.rs index b75701b..e1fb614 100644 --- a/crates/rake/src/router/runtime.rs +++ b/crates/rake/src/router/runtime.rs @@ -1228,6 +1228,16 @@ impl Router { } } + pub(crate) fn logs(&self, after: u64) -> Vec { + self.0 + .collector + .try_crash_tail(128) + .unwrap_or_default() + .into_iter() + .filter(|record| record.sequence > after) + .collect() + } + pub(crate) fn diagnostics( &self, after: u64, diff --git a/crates/rake/src/router/runtime/tests.rs b/crates/rake/src/router/runtime/tests.rs index 11a0348..b495ffe 100644 --- a/crates/rake/src/router/runtime/tests.rs +++ b/crates/rake/src/router/runtime/tests.rs @@ -1333,3 +1333,43 @@ 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()); + let mut fields = std::collections::BTreeMap::new(); + fields.insert("token".into(), serde_json::json!("secret")); + + router.0.collector.record( + "WARN", + "private-target", + "event", + vec!["private-span".into()], + fields, + ); + + 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(records) = query(0) else { + panic!("expected log reply") + }; + + assert_eq!(records.len(), 1); + let json = serde_json::to_string(&records).expect("log JSON"); + + assert!(!json.contains("secret") && !json.contains("private") && !json.contains("token")); + assert_eq!(records[0].level, "WARN"); + assert!(matches!(query(records[0].sequence), Reply::Logs(records) if records.is_empty())); +} diff --git a/crates/rake/tests/local_control.rs b/crates/rake/tests/local_control.rs index 6a2caed..46fa29e 100644 --- a/crates/rake/tests/local_control.rs +++ b/crates/rake/tests/local_control.rs @@ -55,6 +55,9 @@ 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 index adfafa2..bee2a81 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -1,4 +1,93 @@ # Application logging -App logging uses Rake's tracing macros and bounded diagnostic output worker. -Implementation and configuration details are being added with issue #84. +`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. Existing symlink files and nonprivate files/directories +are rejected 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 metadata 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 structural records: sequence, elapsed microseconds, level and +kind. 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. 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 use the crash-record privacy defaults: arbitrary messages, +fields, targets, span names, source paths and user content are omitted. File lines +contain elapsed microseconds, severity and the fixed kind `event`. Rake does not +collect environment values, credentials, request bodies or document content for +these logs. Development stderr and the browser console display tracing fields; +applications must avoid logging sensitive values there. + +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. From 6d3353a315c4a77a1ee6ba45a5090accd42f23f9 Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 21:18:24 +0000 Subject: [PATCH 03/10] fix: preserve log loss counters and portable startup Co-Authored-By: Claude Opus 5.5 --- crates/rake-cli/src/terminal.rs | 6 ++--- crates/rake-diagnostics/src/lib.rs | 27 ++++++++++++++++++++ crates/rake-diagnostics/src/tests.rs | 30 ++++++++++++++++++++++ crates/rake-protocol/src/control.rs | 2 +- crates/rake/src/application.rs | 34 ++++++++++++------------- crates/rake/src/logging.rs | 4 +++ crates/rake/src/router/runtime.rs | 10 ++------ crates/rake/src/router/runtime/tests.rs | 10 +++++--- docs/logging.md | 3 ++- docs/runtime-control.md | 8 +++--- 10 files changed, 98 insertions(+), 36 deletions(-) diff --git a/crates/rake-cli/src/terminal.rs b/crates/rake-cli/src/terminal.rs index 01ad7ea..5c8ec10 100644 --- a/crates/rake-cli/src/terminal.rs +++ b/crates/rake-cli/src/terminal.rs @@ -675,8 +675,8 @@ 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(records)) => { - if let Some(record) = records.last() { + (Query::Logs { after }, Reply::Logs(snapshot)) => { + if let Some(record) = snapshot.records.last() { *after = record.sequence; } } @@ -708,7 +708,7 @@ pub(super) fn run(mut args: Vec) -> Result<()> { 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::Logs(records) if records.is_empty()); + || matches!(&last_reply, Reply::Logs(snapshot) if snapshot.records.is_empty()); if !quiet && value != previous { print(&last_reply, compact)?; diff --git a/crates/rake-diagnostics/src/lib.rs b/crates/rake-diagnostics/src/lib.rs index 2783dc1..a3d63c8 100644 --- a/crates/rake-diagnostics/src/lib.rs +++ b/crates/rake-diagnostics/src/lib.rs @@ -106,6 +106,17 @@ pub struct Snapshot { pub output_dropped: u64, } +/// A bounded structural log tail using the crash-record privacy policy. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct LogSnapshot { + /// At most 128 retained records, oldest first, after the requested sequence. + pub records: Vec, + /// Collector 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 { records: VecDeque, sequence: u64, @@ -206,6 +217,22 @@ impl Collector { ) } + /// Copies a structural 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 + .try_crash_tail(128) + .unwrap_or_default() + .into_iter() + .filter(|record| record.sequence > after) + .collect(), + dropped: self.0.dropped.load(Ordering::Relaxed), + output_dropped: self.0.output_dropped.load(Ordering::Relaxed), + } + } + /// Current collector clock, for development records spanning several observations. #[cfg(feature = "devtools")] #[must_use] diff --git a/crates/rake-diagnostics/src/tests.rs b/crates/rake-diagnostics/src/tests.rs index d0cd82f..7bfd477 100644 --- a/crates/rake-diagnostics/src/tests.rs +++ b/crates/rake-diagnostics/src/tests.rs @@ -161,3 +161,33 @@ fn full_output_queue_drops_without_waiting() { assert_eq!(collector.snapshot().output_dropped, 1); } + +#[test] +fn log_tail_preserves_loss_counts_and_cursor_after_eviction() { + let collector = Collector::new(1); + + for _ in 0..2 { + collector.record( + "INFO", + "private-target", + "event", + Vec::new(), + Default::default(), + ); + } + + 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") + ); +} diff --git a/crates/rake-protocol/src/control.rs b/crates/rake-protocol/src/control.rs index 2341f1b..77f662c 100644 --- a/crates/rake-protocol/src/control.rs +++ b/crates/rake-protocol/src/control.rs @@ -554,7 +554,7 @@ pub enum Reply { /// Bounded diagnostic records, including loss counts. Diagnostics(rake_diagnostics::Snapshot), /// Structural application log tail, with arbitrary text and fields omitted. - Logs(Vec), + Logs(rake_diagnostics::LogSnapshot), } /// Structured protocol errors; transport failures are reported separately as I/O errors. diff --git a/crates/rake/src/application.rs b/crates/rake/src/application.rs index 4fc5881..4433a1e 100644 --- a/crates/rake/src/application.rs +++ b/crates/rake/src/application.rs @@ -1027,23 +1027,23 @@ impl App { }; if let Some(mut config) = self.logging.take() { - if config.level.is_none() { - if 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(); - } + 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(); } } diff --git a/crates/rake/src/logging.rs b/crates/rake/src/logging.rs index 8e12bf0..f58282a 100644 --- a/crates/rake/src/logging.rs +++ b/crates/rake/src/logging.rs @@ -1,8 +1,11 @@ //! 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. @@ -14,6 +17,7 @@ pub struct LogConfig { 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()) } diff --git a/crates/rake/src/router/runtime.rs b/crates/rake/src/router/runtime.rs index e1fb614..eea43a9 100644 --- a/crates/rake/src/router/runtime.rs +++ b/crates/rake/src/router/runtime.rs @@ -1228,14 +1228,8 @@ impl Router { } } - pub(crate) fn logs(&self, after: u64) -> Vec { - self.0 - .collector - .try_crash_tail(128) - .unwrap_or_default() - .into_iter() - .filter(|record| record.sequence > after) - .collect() + pub(crate) fn logs(&self, after: u64) -> crate::diagnostics::LogSnapshot { + self.0.collector.logs_after(after) } pub(crate) fn diagnostics( diff --git a/crates/rake/src/router/runtime/tests.rs b/crates/rake/src/router/runtime/tests.rs index b495ffe..d0543ed 100644 --- a/crates/rake/src/router/runtime/tests.rs +++ b/crates/rake/src/router/runtime/tests.rs @@ -1362,14 +1362,18 @@ fn log_queries_scrub_content_and_advance_the_cursor() { .expect("log query") }; - let Reply::Logs(records) = query(0) else { + let Reply::Logs(snapshot) = query(0) else { panic!("expected log reply") }; - assert_eq!(records.len(), 1); + 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") && !json.contains("private") && !json.contains("token")); assert_eq!(records[0].level, "WARN"); - assert!(matches!(query(records[0].sequence), Reply::Logs(records) if records.is_empty())); + assert!( + matches!(query(records[0].sequence), Reply::Logs(snapshot) if snapshot.records.is_empty()) + ); } diff --git a/docs/logging.md b/docs/logging.md index bee2a81..8ba42c6 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -70,7 +70,8 @@ rake ctl logs --follow ``` These commands query the running app through ctl, without opening arbitrary paths. -Replies are JSON structural records: sequence, elapsed microseconds, level and +Replies are JSON snapshots with cumulative dropped/output-dropped counts and +structural records: sequence, elapsed microseconds, level and kind. 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. Contention or evictions may leave gaps; this diff --git a/docs/runtime-control.md b/docs/runtime-control.md index 5ac43e1..ec5cd4e 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 privacy-safe structural tail with +collector 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 | | --- | --- | From 20adb43a27bca50061362f272f1ae504ed0099b0 Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 21:19:55 +0000 Subject: [PATCH 04/10] fix: restore automatic logging after opting back in Co-Authored-By: Claude Opus 5.5 --- crates/rake/src/application.rs | 4 ++++ docs/logging.md | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/rake/src/application.rs b/crates/rake/src/application.rs index 4433a1e..03d1115 100644 --- a/crates/rake/src/application.rs +++ b/crates/rake/src/application.rs @@ -615,8 +615,12 @@ impl App { } /// 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 } diff --git a/docs/logging.md b/docs/logging.md index 8ba42c6..043f2af 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -20,8 +20,8 @@ For application ID `ID`, the current log is: | 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. Existing symlink files and nonprivate files/directories -are rejected using the same checks as crash storage. Keep the parent 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 From 4d77076e4f4479d55267a1049acdad6982cf4150 Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 21:22:22 +0000 Subject: [PATCH 05/10] fix: create the current log before publishing its path Co-Authored-By: Claude Opus 5.5 --- crates/rake/src/logging.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/rake/src/logging.rs b/crates/rake/src/logging.rs index f58282a..4276817 100644 --- a/crates/rake/src/logging.rs +++ b/crates/rake/src/logging.rs @@ -104,6 +104,13 @@ mod native { } } + let file = private_options() + .append(true) + .create(true) + .open(file_path(&directory, 0))?; + + check_file(&file)?; + Ok(Self { directory, _lock: lock, @@ -238,6 +245,7 @@ mod native { 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") From bec51f4a97b608660e8794e365eb9dab429afcb4 Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 21:27:37 +0000 Subject: [PATCH 06/10] style: satisfy spacing checks for application logging Co-Authored-By: Claude Opus 5.5 --- crates/rake-diagnostics/src/tests.rs | 8 ++++++++ crates/rake/src/application.rs | 1 + crates/rake/src/logging.rs | 8 ++++++++ crates/rake/src/router/runtime/tests.rs | 1 + crates/rake/tests/local_control.rs | 1 + 5 files changed, 19 insertions(+) diff --git a/crates/rake-diagnostics/src/tests.rs b/crates/rake-diagnostics/src/tests.rs index 7bfd477..6cf306d 100644 --- a/crates/rake-diagnostics/src/tests.rs +++ b/crates/rake-diagnostics/src/tests.rs @@ -105,11 +105,15 @@ fn private_output_is_bounded_concurrent_and_omits_payloads() { 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(OutputLayer::new(collector.clone(), &config).expect("worker")); + let dispatch = tracing::Dispatch::new(subscriber); std::thread::scope(|scope| { @@ -146,8 +150,10 @@ fn private_output_is_bounded_concurrent_and_omits_payloads() { #[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 { private: true, started: Instant::now(), @@ -156,7 +162,9 @@ fn full_output_queue_drops_without_waiting() { #[cfg(feature = "devtools")] mirror_marker: false, }; + let subscriber = Registry::default().with(layer); + tracing::subscriber::with_default(subscriber, || tracing::info!("dropped")); assert_eq!(collector.snapshot().output_dropped, 1); diff --git a/crates/rake/src/application.rs b/crates/rake/src/application.rs index 03d1115..a096566 100644 --- a/crates/rake/src/application.rs +++ b/crates/rake/src/application.rs @@ -1040,6 +1040,7 @@ impl App { .ok() .flatten(); } + #[cfg(target_family = "wasm")] { use futures::FutureExt as _; diff --git a/crates/rake/src/logging.rs b/crates/rake/src/logging.rs index 4276817..7ded82e 100644 --- a/crates/rake/src/logging.rs +++ b/crates/rake/src/logging.rs @@ -48,8 +48,10 @@ mod native { #[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) @@ -96,6 +98,7 @@ mod native { if path.try_exists()? { let file = private_options().read(true).open(&path)?; + check_file(&file)?; if file.metadata()?.len() > FILE_BYTES { @@ -122,6 +125,7 @@ mod native { 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 { @@ -174,6 +178,7 @@ mod native { if byte == b'\n' { self.pending.push(byte); let _ = self.line(&self.pending); + self.pending.clear(); } else if self.pending.len() < 255 { self.pending.push(byte); @@ -192,6 +197,7 @@ mod native { match LogWriter::open(directory) { Ok(writer) => { let _ = PATH.set(writer.directory.join("app.log")); + Box::new(writer) } Err(_) => Box::new(io::sink()), @@ -207,6 +213,7 @@ mod native { 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]; @@ -245,6 +252,7 @@ mod native { 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 diff --git a/crates/rake/src/router/runtime/tests.rs b/crates/rake/src/router/runtime/tests.rs index d0543ed..939f418 100644 --- a/crates/rake/src/router/runtime/tests.rs +++ b/crates/rake/src/router/runtime/tests.rs @@ -1340,6 +1340,7 @@ fn log_queries_scrub_content_and_advance_the_cursor() { let router = Router::::new(RouterConfig::default()); let mut fields = std::collections::BTreeMap::new(); + fields.insert("token".into(), serde_json::json!("secret")); router.0.collector.record( diff --git a/crates/rake/tests/local_control.rs b/crates/rake/tests/local_control.rs index 46fa29e..7f13555 100644 --- a/crates/rake/tests/local_control.rs +++ b/crates/rake/tests/local_control.rs @@ -57,6 +57,7 @@ fn native_endpoint_round_trip_bounds_and_discovery_lifetime() { 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 { From 4f4da194c9f76dc91197e8bc73d513cbccb80743 Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 23:32:57 +0000 Subject: [PATCH 07/10] feat: retain useful redacted application log lines Add UTC timestamps, target, messages and fields to bounded 4 KiB log records. Share the formatted line with ctl, redact secret-named fields, escape values and mark UTF-8-safe truncation. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/rake-diagnostics/Cargo.toml | 1 + crates/rake-diagnostics/src/lib.rs | 144 +++++++++++++------ crates/rake-diagnostics/src/logging.rs | 181 ++++++++++++++++++++++++ crates/rake-diagnostics/src/tests.rs | 111 +++++++++++---- crates/rake-protocol/src/control.rs | 6 +- crates/rake/src/logging.rs | 63 ++++++++- crates/rake/src/router/runtime/tests.rs | 21 ++- docs/logging.md | 49 +++++-- docs/runtime-control.md | 4 +- 10 files changed, 489 insertions(+), 92 deletions(-) create mode 100644 crates/rake-diagnostics/src/logging.rs diff --git a/Cargo.lock b/Cargo.lock index f9cbef0..09f09e0 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-diagnostics/Cargo.toml b/crates/rake-diagnostics/Cargo.toml index 48e6847..430e557 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 a3d63c8..c3e59ab 100644 --- a/crates/rake-diagnostics/src/lib.rs +++ b/crates/rake-diagnostics/src/lib.rs @@ -20,6 +20,8 @@ #[cfg(feature = "devtools")] pub mod http; +mod logging; +pub use logging::MAX_LOG_RECORD_BYTES; use std::collections::{BTreeMap, VecDeque}; use std::fmt; @@ -106,18 +108,30 @@ pub struct Snapshot { pub output_dropped: u64, } -/// A bounded structural log tail using the crash-record privacy policy. +/// 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, - /// Collector records lost to eviction or contention since startup. + 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")] @@ -131,6 +145,7 @@ struct Inner { capacity: usize, dropped: AtomicU64, output_dropped: AtomicU64, + logs_dropped: AtomicU64, started: Instant, next_span: AtomicU64, #[cfg(feature = "devtools")] @@ -153,6 +168,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")] @@ -163,6 +181,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")] @@ -217,22 +236,68 @@ impl Collector { ) } - /// Copies a structural log tail after an exclusive sequence cursor. + /// 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 - .try_crash_tail(128) - .unwrap_or_default() - .into_iter() - .filter(|record| record.sequence > after) - .collect(), - dropped: self.0.dropped.load(Ordering::Relaxed), + .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] @@ -340,7 +405,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. @@ -502,7 +567,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)] @@ -680,6 +745,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(), @@ -786,7 +865,7 @@ impl DiagnosticsConfig { } /// Replaces stderr with a writer created on the bounded output worker. - /// File output contains structural metadata only, just like crash diagnostics. + /// File output uses bounded single-line records with secret-named fields redacted. #[cfg(not(target_family = "wasm"))] pub fn log_writer( mut self, @@ -809,8 +888,10 @@ impl DiagnosticsConfig { tracing::subscriber::set_global_default( Registry::default() - .with(self.collector.layer()) - .with(OutputLayer::new(self.collector.clone(), self)?) + .with(CollectorLayer( + self.collector.clone(), + Some(OutputLayer::new(self.collector.clone(), self)?), + )) .with( std::env::var("RAKE_LOG") .ok() @@ -837,8 +918,7 @@ pub enum DiagnosticsError { } struct OutputLayer { - private: bool, - started: Instant, + file: bool, #[cfg(all(feature = "devtools", not(target_family = "wasm")))] mirror_marker: bool, #[cfg(not(target_family = "wasm"))] @@ -854,7 +934,7 @@ impl OutputLayer { let (sender, receiver) = std::sync::mpsc::sync_channel::(1024); let output = config.output.clone(); - let private = output.is_some(); + let file = output.is_some(); std::thread::Builder::new() .name("rake-diagnostics".into()) @@ -872,8 +952,7 @@ impl OutputLayer { .map_err(DiagnosticsError::OutputWorker)?; Ok(Self { - private, - started: Instant::now(), + file, sender, collector, #[cfg(feature = "devtools")] @@ -886,28 +965,13 @@ impl OutputLayer { { let _ = (collector, config); - Ok(Self { - private: false, - started: Instant::now(), - }) + Ok(Self { file: false }) } } -} -impl Layer for OutputLayer { - fn on_event(&self, event: &Event<'_>, _cx: Context<'_, S>) { - let mut fields = Fields::default(); - - if !self.private { - event.record(&mut fields); - } - - let text = if self.private { - format!( - "{}us {} event", - self.started.elapsed().as_micros(), - event.metadata().level() - ) + fn emit(&self, event: &Event<'_>, fields: &Fields, line: &str) { + let text = if self.file { + line.to_owned() } else { format!( "{} {} {:?}", @@ -918,7 +982,7 @@ impl Layer for OutputLayer { }; #[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 0000000..a29a9e1 --- /dev/null +++ b/crates/rake-diagnostics/src/logging.rs @@ -0,0 +1,181 @@ +//! 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 6cf306d..353eb56 100644 --- a/crates/rake-diagnostics/src/tests.rs +++ b/crates/rake-diagnostics/src/tests.rs @@ -5,23 +5,23 @@ use tracing_subscriber::prelude::*; -use super::{Collector, DiagnosticsConfig, Instant, OutputLayer, Registry}; +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 { - private: false, - started: Instant::now(), + 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"); @@ -84,7 +84,7 @@ fn crash_tail_keeps_only_bounded_structural_metadata() { } #[test] -fn private_output_is_bounded_concurrent_and_omits_payloads() { +fn file_output_is_concurrent_redacted_and_matches_ctl() { use std::io::{self, Write}; use std::sync::{Mutex, mpsc}; use std::time::Duration; @@ -111,8 +111,10 @@ fn private_output_is_bounded_concurrent_and_omits_payloads() { let collector = config.shared_collector(); - let subscriber = - Registry::default().with(OutputLayer::new(collector.clone(), &config).expect("worker")); + let subscriber = Registry::default().with(CollectorLayer( + collector.clone(), + Some(OutputLayer::new(collector.clone(), &config).expect("worker")), + )); let dispatch = tracing::Dispatch::new(subscriber); @@ -142,8 +144,26 @@ fn private_output_is_bounded_concurrent_and_omits_payloads() { let output = String::from_utf8(output).expect("UTF-8 output"); assert_eq!(output.lines().count(), 80); - assert!(output.lines().all(|line| line.ends_with(" WARN event"))); - assert!(!output.contains("secret") && !output.contains("private user content")); + 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); } @@ -155,15 +175,14 @@ fn full_output_queue_drops_without_waiting() { let collector = Collector::default(); let layer = OutputLayer { - private: true, - started: Instant::now(), + file: true, sender, collector: collector.clone(), #[cfg(feature = "devtools")] mirror_marker: false, }; - let subscriber = Registry::default().with(layer); + let subscriber = Registry::default().with(CollectorLayer(collector.clone(), Some(layer))); tracing::subscriber::with_default(subscriber, || tracing::info!("dropped")); @@ -174,15 +193,13 @@ fn full_output_queue_drops_without_waiting() { fn log_tail_preserves_loss_counts_and_cursor_after_eviction() { let collector = Collector::new(1); - for _ in 0..2 { - collector.record( - "INFO", - "private-target", - "event", - Vec::new(), - Default::default(), - ); - } + 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); @@ -199,3 +216,49 @@ fn log_tail_preserves_loss_counts_and_cursor_after_eviction() { .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 77f662c..20f1268 100644 --- a/crates/rake-protocol/src/control.rs +++ b/crates/rake-protocol/src/control.rs @@ -373,9 +373,9 @@ pub enum Query { /// Selects the response rather than the request body. response: bool, }, - /// Privacy-safe application log metadata after a collector sequence. + /// Redacted formatted application logs after a log sequence. Logs { - /// Exclusive collector sequence. + /// Exclusive log sequence. after: u64, }, /// Bounded records for logs, requests and traces with observable loss counts. @@ -553,7 +553,7 @@ pub enum Reply { Event(RuntimeEvent), /// Bounded diagnostic records, including loss counts. Diagnostics(rake_diagnostics::Snapshot), - /// Structural application log tail, with arbitrary text and fields omitted. + /// Redacted application log lines, matching the file output. Logs(rake_diagnostics::LogSnapshot), } diff --git a/crates/rake/src/logging.rs b/crates/rake/src/logging.rs index 7ded82e..4e0c55b 100644 --- a/crates/rake/src/logging.rs +++ b/crates/rake/src/logging.rs @@ -68,6 +68,7 @@ mod native { directory: PathBuf, _lock: fs::File, pending: Vec, + truncated: bool, } impl LogWriter { @@ -118,6 +119,7 @@ mod native { directory, _lock: lock, pending: Vec::new(), + truncated: false, }) } @@ -176,12 +178,25 @@ mod native { 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(); - } else if self.pending.len() < 255 { + self.truncated = false; + } else if self.pending.len() < crate::diagnostics::MAX_LOG_RECORD_BYTES - 1 { self.pending.push(byte); + } else { + self.truncated = true; } } @@ -208,6 +223,52 @@ mod native { 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"); diff --git a/crates/rake/src/router/runtime/tests.rs b/crates/rake/src/router/runtime/tests.rs index 939f418..e273139 100644 --- a/crates/rake/src/router/runtime/tests.rs +++ b/crates/rake/src/router/runtime/tests.rs @@ -1339,17 +1339,12 @@ fn log_queries_scrub_content_and_advance_the_cursor() { use crate::control::{Message, PROTOCOL_VERSION, Query, Reply, Request}; let router = Router::::new(RouterConfig::default()); - let mut fields = std::collections::BTreeMap::new(); + use tracing_subscriber::prelude::*; + let subscriber = tracing_subscriber::registry().with(router.0.collector.layer()); - fields.insert("token".into(), serde_json::json!("secret")); - - router.0.collector.record( - "WARN", - "private-target", - "event", - vec!["private-span".into()], - fields, - ); + tracing::subscriber::with_default(subscriber, || { + crate::warn!(target: "example::worker", token = "secret", "application message"); + }); let query = |after| { router @@ -1372,8 +1367,10 @@ fn log_queries_scrub_content_and_advance_the_cursor() { let records = snapshot.records; let json = serde_json::to_string(&records).expect("log JSON"); - assert!(!json.contains("secret") && !json.contains("private") && !json.contains("token")); - assert_eq!(records[0].level, "WARN"); + 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/docs/logging.md b/docs/logging.md index 043f2af..024e3b4 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -31,7 +31,7 @@ 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 metadata lines and never wait for +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, @@ -71,22 +71,51 @@ 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 -structural records: sequence, elapsed microseconds, level and -kind. Follow advances the sequence cursor and suppresses empty replies, using the +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. Contention or evictions may leave gaps; this +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 use the crash-record privacy defaults: arbitrary messages, -fields, targets, span names, source paths and user content are omitted. File lines -contain elapsed microseconds, severity and the fixed kind `event`. Rake does not -collect environment values, credentials, request bodies or document content for -these logs. Development stderr and the browser console display tracing fields; -applications must avoid logging sensitive values there. +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 diff --git a/docs/runtime-control.md b/docs/runtime-control.md index ec5cd4e..8179282 100644 --- a/docs/runtime-control.md +++ b/docs/runtime-control.md @@ -210,8 +210,8 @@ 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. -`rake ctl logs` and `logs follow` expose a privacy-safe structural tail with -collector sequences and cumulative dropped/output-dropped counts; see +`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. From c319cfde1fa97b82581482643cb10fc38e3c90c7 Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 23:32:57 +0000 Subject: [PATCH 08/10] fix: keep runtime diagnostics free of user content Replace raw framework error payloads with static error types. Omit tray diagnostic bodies, document AST/text dumps, URL strings, response-header values and browser clipboard exception details from runtime logging. Co-Authored-By: Claude Opus 5.5 --- crates/rake-ui/src/view/paragraph/layout.rs | 10 ++- crates/rake/src/application.rs | 15 +++- crates/rake/src/application/managed.rs | 30 +++++-- crates/rake/src/application/managed/window.rs | 5 +- crates/rake/src/control/local.rs | 5 +- crates/rake/src/control/mod.rs | 20 ++++- crates/rake/src/control/web.rs | 5 +- crates/rake/src/crash/startup.rs | 10 ++- crates/rake/src/menus.rs | 7 +- crates/rake/src/router/navigation_view.rs | 5 +- crates/rake/src/router/runtime/quit.rs | 10 ++- crates/rake/src/router/runtime/updates.rs | 5 +- crates/rake/src/router/view.rs | 84 ++++++++++++------- crates/rake/src/surface.rs | 5 +- crates/rake/src/surface/native.rs | 5 +- crates/rake/src/tray.rs | 68 +++++++++++---- crates/rake/src/window_state.rs | 10 ++- vendor/gpui-base/src/input/base/state.rs | 5 +- vendor/gpui-base/src/text/format/markdown.rs | 16 ++-- vendor/gpui-base/src/text/node.rs | 2 +- vendor/gpui-pre-web/src/dispatcher.rs | 15 +++- vendor/gpui-pre-web/src/events.rs | 11 ++- vendor/gpui-pre-web/src/http_client.rs | 16 ++-- vendor/gpui-pre-web/src/ime_mirror.rs | 10 ++- vendor/gpui-pre-web/src/platform.rs | 25 ++++-- vendor/gpui-pre-web/src/text_system.rs | 10 ++- vendor/gpui-pre-web/src/window.rs | 15 +++- 27 files changed, 311 insertions(+), 113 deletions(-) diff --git a/crates/rake-ui/src/view/paragraph/layout.rs b/crates/rake-ui/src/view/paragraph/layout.rs index 03b96d5..782d59d 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/src/application.rs b/crates/rake/src/application.rs index a096566..84c7ae9 100644 --- a/crates/rake/src/application.rs +++ b/crates/rake/src/application.rs @@ -1100,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" + ); } } }); @@ -1136,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" + ), } } }) @@ -1176,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 5742219..14dac3a 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 f77d5b8..0daa6d7 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 612dbe2..2f1278f 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 be326bc..c8f22ab 100644 --- a/crates/rake/src/control/mod.rs +++ b/crates/rake/src/control/mod.rs @@ -792,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" + ), } } @@ -803,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 121a9a1..19e06d9 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/startup.rs b/crates/rake/src/crash/startup.rs index 9a9e8b8..89f8fd6 100644 --- a/crates/rake/src/crash/startup.rs +++ b/crates/rake/src/crash/startup.rs @@ -41,7 +41,10 @@ impl CrashReports { }); if let Err(error) = result { - tracing::warn!(%error, "default crash recording unavailable; startup continues"); + tracing::warn!( + error_type = std::any::type_name_of_val(&error), + "default crash recording unavailable; startup continues" + ); } } Self::Disabled => {} @@ -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_type = std::any::type_name_of_val(&error), + "crash delivery failed; waiting record retained" + ); } }); } diff --git a/crates/rake/src/menus.rs b/crates/rake/src/menus.rs index 6462f76..7509a25 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 5a382dd..4b640c0 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/quit.rs b/crates/rake/src/router/runtime/quit.rs index 2c6508e..e5e0a40 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/updates.rs b/crates/rake/src/router/runtime/updates.rs index a142156..f1587fa 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 4fbd00b..90f5633 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 ad3f88a..cae126a 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 cdd0c58..ce3ae1d 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 da79c1e..ff28c74 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 e3d9730..81a0911 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/vendor/gpui-base/src/input/base/state.rs b/vendor/gpui-base/src/input/base/state.rs index 3d0fdea..eabd6fd 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 7fa574d..24012c1 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 c8a8c85..f78fa16 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 f529d8e..a78800c 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 c3f8cd8..3219fd8 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 848c9df..daf0852 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 5cb08b5..950556c 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 b496aa4..561807d 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 e8ce869..91828dc 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 ddd9095..b9f6823 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) + ); } } From f0bd7971878416e72ece490b26da15c3c4d9f532 Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Sun, 15 Nov 2026 23:40:16 +0000 Subject: [PATCH 09/10] style: fix rich log record spacing Co-Authored-By: Claude Opus 5.5 --- crates/rake-diagnostics/src/lib.rs | 1 + crates/rake-diagnostics/src/logging.rs | 1 + crates/rake-diagnostics/src/tests.rs | 2 ++ crates/rake/src/logging.rs | 1 + crates/rake/src/router/runtime/tests.rs | 1 + 5 files changed, 6 insertions(+) diff --git a/crates/rake-diagnostics/src/lib.rs b/crates/rake-diagnostics/src/lib.rs index c3e59ab..cbace78 100644 --- a/crates/rake-diagnostics/src/lib.rs +++ b/crates/rake-diagnostics/src/lib.rs @@ -21,6 +21,7 @@ #[cfg(feature = "devtools")] pub mod http; mod logging; + pub use logging::MAX_LOG_RECORD_BYTES; use std::collections::{BTreeMap, VecDeque}; diff --git a/crates/rake-diagnostics/src/logging.rs b/crates/rake-diagnostics/src/logging.rs index a29a9e1..ac17a9c 100644 --- a/crates/rake-diagnostics/src/logging.rs +++ b/crates/rake-diagnostics/src/logging.rs @@ -61,6 +61,7 @@ pub(super) fn format( 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) diff --git a/crates/rake-diagnostics/src/tests.rs b/crates/rake-diagnostics/src/tests.rs index 353eb56..06fb462 100644 --- a/crates/rake-diagnostics/src/tests.rs +++ b/crates/rake-diagnostics/src/tests.rs @@ -244,6 +244,7 @@ fn escaped_log_tail_stays_below_the_transport_budget() { 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, @@ -251,6 +252,7 @@ fn development_stderr_format_is_unchanged() { #[cfg(feature = "devtools")] mirror_marker: false, }; + let subscriber = Registry::default().with(CollectorLayer(collector, Some(output))); tracing::subscriber::with_default(subscriber, || { diff --git a/crates/rake/src/logging.rs b/crates/rake/src/logging.rs index 4e0c55b..4b68fb9 100644 --- a/crates/rake/src/logging.rs +++ b/crates/rake/src/logging.rs @@ -181,6 +181,7 @@ mod native { 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); diff --git a/crates/rake/src/router/runtime/tests.rs b/crates/rake/src/router/runtime/tests.rs index e273139..d12a656 100644 --- a/crates/rake/src/router/runtime/tests.rs +++ b/crates/rake/src/router/runtime/tests.rs @@ -1339,6 +1339,7 @@ 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()); From 3de293847323cc139deb3988297b5dcf941c2007 Mon Sep 17 00:00:00 2001 From: Yurii Hulyk Date: Mon, 16 Nov 2026 10:49:51 +0000 Subject: [PATCH 10/10] fix: restore safe Web crash delivery categories Web delivery returns fixed categories rather than sink payloads. Preserve the warning error field consumed by the unchanged browser regression test. Co-Authored-By: Claude Opus 5.5 --- crates/rake/src/crash/startup.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/rake/src/crash/startup.rs b/crates/rake/src/crash/startup.rs index 89f8fd6..dc0206a 100644 --- a/crates/rake/src/crash/startup.rs +++ b/crates/rake/src/crash/startup.rs @@ -63,7 +63,7 @@ impl CrashReports { if let Err(error) = reporter.deliver(sink).await { // Web errors carry only fixed, privacy-safe category messages. tracing::warn!( - error_type = std::any::type_name_of_val(&error), + %error, "crash delivery failed; waiting record retained" ); }