Skip to content

Commit 44d1b14

Browse files
committed
Separate panic logging code
Move the panic logging code to a function separate from `on_panic` and simplify the code to decide whether the backtrace should be logged.
1 parent 07ca1ab commit 44d1b14

File tree

1 file changed

+19
-22
lines changed

1 file changed

+19
-22
lines changed

src/libstd/panicking.rs

+19-22
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ thread_local! {
2424
}
2525
}
2626

27-
pub fn on_panic(obj: &(Any+Send), file: &'static str, line: u32) {
27+
fn log_panic(obj: &(Any+Send), file: &'static str, line: u32,
28+
log_backtrace: bool) {
2829
let msg = match obj.downcast_ref::<&'static str>() {
2930
Some(s) => *s,
3031
None => match obj.downcast_ref::<String>() {
@@ -35,37 +36,33 @@ pub fn on_panic(obj: &(Any+Send), file: &'static str, line: u32) {
3536
let mut err = Stderr::new().ok();
3637
let thread = thread_info::current_thread();
3738
let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
39+
40+
let write = |err: &mut ::io::Write| {
41+
let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
42+
name, msg, file, line);
43+
if log_backtrace {
44+
let _ = backtrace::write(err);
45+
}
46+
};
47+
3848
let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
3949
match (prev, err.as_mut()) {
4050
(Some(mut stderr), _) => {
4151
// FIXME: what to do when the thread printing panics?
42-
let _ = writeln!(stderr,
43-
"thread '{}' panicked at '{}', {}:{}\n",
44-
name, msg, file, line);
45-
if backtrace::log_enabled() {
46-
let _ = backtrace::write(&mut *stderr);
47-
}
52+
write(&mut *stderr);
4853
let mut s = Some(stderr);
4954
LOCAL_STDERR.with(|slot| {
5055
*slot.borrow_mut() = s.take();
5156
});
5257
}
53-
(None, Some(ref mut err)) => {
54-
let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
55-
name, msg, file, line);
56-
if backtrace::log_enabled() {
57-
let _ = backtrace::write(err);
58-
}
59-
}
58+
(None, Some(ref mut err)) => { write(err) }
6059
_ => {}
6160
}
61+
}
6262

63-
// If this is a double panic, make sure that we printed a backtrace
64-
// for this panic.
65-
match err {
66-
Some(ref mut err) if unwind::panicking() && !backtrace::log_enabled() => {
67-
let _ = backtrace::write(err);
68-
}
69-
_ => {}
70-
}
63+
pub fn on_panic(obj: &(Any+Send), file: &'static str, line: u32) {
64+
// If this is a double panic, make sure that we print a backtrace
65+
// for this panic. Otherwise only print it if logging is enabled.
66+
let log_backtrace = unwind::panicking() || backtrace::log_enabled();
67+
log_panic(obj, file, line, log_backtrace);
7168
}

0 commit comments

Comments
 (0)