From 1fba68bfe238629733b49d4c9d576556f7788585 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 27 May 2023 15:33:02 +0300 Subject: [PATCH] Catch exceptions from async logger. Fix #2618 --- include/spdlog/async_logger-inl.h | 32 +++++++++++++++++++------------ tests/test_async.cpp | 10 +++++++++- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/include/spdlog/async_logger-inl.h b/include/spdlog/async_logger-inl.h index a1c27a59..13da5940 100644 --- a/include/spdlog/async_logger-inl.h +++ b/include/spdlog/async_logger-inl.h @@ -26,27 +26,35 @@ SPDLOG_INLINE spdlog::async_logger::async_logger( // send the log message to the thread pool SPDLOG_INLINE void spdlog::async_logger::sink_it_(const details::log_msg &msg) { - if (auto pool_ptr = thread_pool_.lock()) + SPDLOG_TRY { - pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); - } - else - { - throw_spdlog_ex("async log: thread pool doesn't exist anymore"); + if (auto pool_ptr = thread_pool_.lock()) + { + pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); + } + else + { + throw_spdlog_ex("async log: thread pool doesn't exist anymore"); + } } + SPDLOG_LOGGER_CATCH(msg.source) } // send flush request to the thread pool SPDLOG_INLINE void spdlog::async_logger::flush_() { - if (auto pool_ptr = thread_pool_.lock()) + SPDLOG_TRY { - pool_ptr->post_flush(shared_from_this(), overflow_policy_); - } - else - { - throw_spdlog_ex("async flush: thread pool doesn't exist anymore"); + if (auto pool_ptr = thread_pool_.lock()) + { + pool_ptr->post_flush(shared_from_this(), overflow_policy_); + } + else + { + throw_spdlog_ex("async flush: thread pool doesn't exist anymore"); + } } + SPDLOG_LOGGER_CATCH(source_loc()) } // diff --git a/tests/test_async.cpp b/tests/test_async.cpp index 5265bca4..06c5c921 100644 --- a/tests/test_async.cpp +++ b/tests/test_async.cpp @@ -185,6 +185,14 @@ TEST_CASE("to_file multi-workers", "[async]") logger->info("Hello message #{}", j); } } - require_message_count(TEST_FILENAME, messages); } + +TEST_CASE("bad_tp", "[async]") +{ + auto test_sink = std::make_shared(); + std::shared_ptr const empty_tp; + auto logger = std::make_shared("as", test_sink, empty_tp); + logger->info("Please throw an exception"); + REQUIRE(test_sink->msg_counter() == 0); +}