Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 60 additions & 6 deletions crates/xcl/src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,37 @@ pub fn init(path: Option<&Path>, level: Level, echo_stderr: bool) {
LEVEL.store(level as u8, Ordering::Relaxed);
ECHO.store(echo_stderr, Ordering::Relaxed);
if let Some(p) = path {
if let Some(dir) = p.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(f) = File::create(p) {
if let Ok(mut g) = FILE.lock() {
*g = Some(f);
// a log that cannot be opened is said once on stderr: `xlog_*` would go nowhere, and the
// console has already been given its path (#2277); the run goes on without it
match open(p) {
Ok(f) => {
if let Ok(mut g) = FILE.lock() {
*g = Some(f);
}
}
Err(e) => warn(&e),
}
}
}

/// `xcl: <msg>` on stderr, best effort: a broken stderr is not one more failure to die of
/// (`eprintln!` panics on it), and these messages are said when the log is already gone.
pub(crate) fn warn(msg: &str) {
warn_to(&mut std::io::stderr(), msg);
}

fn warn_to(w: &mut dyn Write, msg: &str) {
let _ = writeln!(w, "xcl: {msg}");
}

/// The log file at `p`, its folder made first; the error names the path and the OS error.
fn open(p: &Path) -> Result<File, String> {
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("cannot create the log folder {}: {e}", dir.display()))?;
}
File::create(p).map_err(|e| format!("cannot open the log {}: {e}", p.display()))
}

pub fn enabled(level: Level) -> bool {
level as u8 <= LEVEL.load(Ordering::Relaxed)
}
Expand Down Expand Up @@ -121,6 +141,24 @@ macro_rules! xlog_trace { ($($a:tt)*) => { if $crate::log::enabled($crate::log::
mod tests {
use super::*;

/// A stderr that cannot be written (a closed pipe) is not a panic.
#[test]
fn a_warning_to_a_broken_stderr_is_dropped() {
struct Broken;
impl Write for Broken {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(std::io::ErrorKind::BrokenPipe.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Err(std::io::ErrorKind::BrokenPipe.into())
}
}
warn_to(&mut Broken, "cannot create the log folder x");
let mut out = Vec::new();
warn_to(&mut out, "cannot create the log folder x");
assert_eq!(out, b"xcl: cannot create the log folder x\n");
}

#[test]
fn a_panic_is_in_the_log() {
let path = std::env::temp_dir().join(format!("xcl-log-panics-{}.log", std::process::id()));
Expand All @@ -133,4 +171,20 @@ mod tests {
assert!(died.is_err());
assert!(log.contains("thread 'xcl-dies' panicked at ") && log.contains("gone for the run"), "the log: {log:?}");
}

#[test]
fn a_log_that_cannot_be_opened_names_its_path() {
let dir = std::env::temp_dir().join(format!("xcl-log-open-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// a file where the log folder should be: neither the folder nor the log can be made
let blocker = dir.join("not-a-folder");
std::fs::write(&blocker, "x").unwrap();
let bad = blocker.join("logs").join("xcl.log");
let e = open(&bad).unwrap_err();
assert!(e.starts_with("cannot create the log folder ") && e.contains("not-a-folder"), "{e}");
let good = dir.join("logs").join("xcl.log");
assert!(open(&good).is_ok());
assert!(good.is_file());
let _ = std::fs::remove_dir_all(&dir);
}
}
29 changes: 28 additions & 1 deletion crates/xcl/src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,23 @@ pub fn write_final(crash: Option<String>) {
let Some(boot) = crate::state::boot() else { return };
let r = build();
if let Ok(s) = serde_json::to_string_pretty(&r) {
let _ = std::fs::write(boot.report_path(), s);
// said once on stderr: a report that is not there would otherwise look like a silent
// crash, and its log may be missing for the same reason (#2277)
if let Err(e) = save(&boot.report_path(), &s) {
if !WRITE_FAILED.swap(true, Ordering::Relaxed) {
crate::log::warn(&e);
}
}
}
}

static WRITE_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Write the report text to `path`; the error names the path and the OS error.
fn save(path: &std::path::Path, text: &str) -> Result<(), String> {
std::fs::write(path, text).map_err(|e| format!("cannot write the report {}: {e}", path.display()))
}

pub fn load(path: &std::path::Path) -> Option<Report> {
serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
}
Expand All @@ -212,4 +225,18 @@ mod tests {
assert_eq!(CRASH.lock().unwrap().as_deref(), Some("boom"));
*CRASH.lock().unwrap() = None;
}

#[test]
fn a_report_that_cannot_be_written_names_its_path() {
let dir = std::env::temp_dir().join(format!("xcl-report-save-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let blocker = dir.join("not-a-folder");
std::fs::write(&blocker, "x").unwrap();
let e = save(&blocker.join("report.json"), "{}").unwrap_err();
assert!(e.starts_with("cannot write the report ") && e.contains("not-a-folder"), "{e}");
let good = dir.join("report.json");
save(&good, "{}").unwrap();
assert_eq!(std::fs::read_to_string(&good).unwrap(), "{}");
let _ = std::fs::remove_dir_all(&dir);
}
}
Loading