Skip to content

Commit 8e9bd61

Browse files
committed
Replace eprintln! with writeln! to avoid broken stdio panic
1 parent 8fac16d commit 8e9bd61

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

spdlog/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ rustc_version = "0.4.0"
9494
name = "global_async_pool_sink"
9595
harness = false
9696
required-features = ["multi-thread"]
97+
[[test]]
98+
name = "broken_stdio"
99+
harness = false
97100

98101
[[bench]]
99102
name = "spdlog_rs"

spdlog/src/lib.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,9 @@ use std::{
322322
borrow::Cow,
323323
env::{self, VarError},
324324
ffi::OsStr,
325-
fmt, panic,
325+
fmt,
326+
io::{self, Write},
327+
panic,
326328
result::Result as StdResult,
327329
};
328330

@@ -769,7 +771,11 @@ fn default_error_handler(from: impl AsRef<str>, error: Error) {
769771
.format("%Y-%m-%d %H:%M:%S.%3f")
770772
.to_string();
771773

772-
eprintln!(
774+
// https://github.com/SpriteOvO/spdlog-rs/discussions/87
775+
//
776+
// Don't use `eprintln!` here, as it may fail to write and then panic.
777+
let _ = writeln!(
778+
io::stderr(),
773779
"[*** SPDLOG-RS UNHANDLED ERROR ***] [{}] [{}] {}",
774780
date,
775781
from.as_ref(),

spdlog/tests/broken_stdio.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// https://github.com/SpriteOvO/spdlog-rs/discussions/87
2+
//
3+
// Rust's print macros will panic if a write fails, we should avoid using
4+
// print macros internally.
5+
fn main() {
6+
#[cfg(target_family = "unix")]
7+
{
8+
let dev_full = std::ffi::CString::new("/dev/full").unwrap();
9+
unsafe {
10+
let fd = libc::open(dev_full.as_ptr(), libc::O_WRONLY);
11+
libc::dup2(fd, libc::STDOUT_FILENO);
12+
libc::dup2(fd, libc::STDERR_FILENO);
13+
}
14+
}
15+
// TODO: Other platforms?
16+
spdlog::info!("will panic if print macros are used internally");
17+
spdlog::error!("will panic if print macros are used internally");
18+
}

0 commit comments

Comments
 (0)