Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stop swallowing exceptions #58

Merged
merged 3 commits into from
Dec 19, 2024
Merged
Changes from 2 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
25 changes: 21 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,14 +515,20 @@ impl Log for Logger {
let cache = self.lookup(record.target());

if self.enabled_inner(record.metadata(), &cache) {
Python::with_gil(|py| match self.log_inner(py, record, &cache) {
Python::with_gil(|py| {
// If an exception were triggered before this attempt to log,
// store it to the side for now and restore it afterwards.
let maybe_existing_exception = PyErr::take(py);
match self.log_inner(py, record, &cache) {

Ok(Some(logger)) => {
let filter = match self.caching {
Caching::Nothing => unreachable!(),
Caching::Loggers => LevelFilter::max(),
Caching::LoggersAndLevels => extract_max_level(logger.bind(py))
.unwrap_or_else(|e| {
e.print(py);
// See detailed NOTE below
e.restore(py);
LevelFilter::max()
}),
};
Expand All @@ -531,8 +537,19 @@ impl Log for Logger {
self.store_to_cache(py, record.target(), entry);
}
Ok(None) => (),
Err(e) => e.print(py),
})
Err(e) => {
// NOTE: If an exception was triggered _during_ logging, restore it as current Python exception.
// We have to use PyErr::restore because we cannot return a PyResult from the Log trait's log method.
e.restore(py);
},
};

// If there was a prior exception, restore it now
// This ensures that the earliest thrown exception will be the one that's visible to the caller.
if let Some(e) = maybe_existing_exception {
e.restore(py);
}
})
}
}

Expand Down
Loading