Skip to content

Commit 050b901

Browse files
committed
Only set panic hook and log level once.
1 parent 7954b8b commit 050b901

File tree

1 file changed

+28
-27
lines changed

1 file changed

+28
-27
lines changed

src/logging.rs

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -62,31 +62,32 @@ impl log::Log for Px4Logger {
6262
static LOGGER: Px4Logger = Px4Logger;
6363

6464
pub unsafe fn init(modulename: &'static [u8]) {
65-
log::set_logger(&LOGGER).ok();
66-
log::set_max_level(log::LevelFilter::Info);
67-
std::panic::set_hook(Box::new(move |info: &std::panic::PanicInfo| {
68-
let payload: &str = if let Some(s) = info.payload().downcast_ref::<&'static str>() {
69-
s
70-
} else if let Some(s) = info.payload().downcast_ref::<String>() {
71-
&s
72-
} else {
73-
"[panic message not available]"
74-
};
75-
let mut message = String::new();
76-
let thread = std::thread::current();
77-
if let Some(name) = thread.name() {
78-
write!(message, "thread '{}' ", name).unwrap();
79-
}
80-
write!(message, "panicked at '{}'", payload).unwrap();
81-
if let Some(loc) = info.location() {
82-
write!(message, ", {}", loc).unwrap();
83-
}
84-
message.push('\0');
85-
px4_log_modulename(
86-
LogLevel::Panic as i32,
87-
modulename.as_ptr(),
88-
"%s\0".as_ptr(),
89-
message.as_ptr(),
90-
);
91-
}));
65+
if log::set_logger(&LOGGER).is_ok() {
66+
log::set_max_level(log::LevelFilter::Info);
67+
std::panic::set_hook(Box::new(move |info: &std::panic::PanicInfo| {
68+
let payload: &str = if let Some(s) = info.payload().downcast_ref::<&'static str>() {
69+
s
70+
} else if let Some(s) = info.payload().downcast_ref::<String>() {
71+
&s
72+
} else {
73+
"[panic message not available]"
74+
};
75+
let mut message = String::new();
76+
let thread = std::thread::current();
77+
if let Some(name) = thread.name() {
78+
write!(message, "thread '{}' ", name).unwrap();
79+
}
80+
write!(message, "panicked at '{}'", payload).unwrap();
81+
if let Some(loc) = info.location() {
82+
write!(message, ", {}", loc).unwrap();
83+
}
84+
message.push('\0');
85+
px4_log_modulename(
86+
LogLevel::Panic as i32,
87+
modulename.as_ptr(),
88+
"%s\0".as_ptr(),
89+
message.as_ptr(),
90+
);
91+
}));
92+
}
9293
}

0 commit comments

Comments
 (0)