From bc2eed7913781ee7d82956e2f30bee637dcb8b9d Mon Sep 17 00:00:00 2001 From: gabime Date: Fri, 17 Jan 2025 13:30:37 +0200 Subject: [PATCH] Added custom error handler support to async sink --- include/spdlog/details/err_helper.h | 5 ++--- include/spdlog/sinks/async_sink.h | 2 +- src/sinks/async_sink.cpp | 8 ++++++-- tests/test_async.cpp | 14 ++++++++++++++ 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/include/spdlog/details/err_helper.h b/include/spdlog/details/err_helper.h index 6ae8815a..3b6bdcaa 100644 --- a/include/spdlog/details/err_helper.h +++ b/include/spdlog/details/err_helper.h @@ -18,6 +18,5 @@ public: void handle_unknown_ex(const std::string& origin, const source_loc& loc) const noexcept; void set_err_handler(err_handler handler); }; - - -}} // namespace spdlog::details +} // namespace details +} // namespace spdlog diff --git a/include/spdlog/sinks/async_sink.h b/include/spdlog/sinks/async_sink.h index 35ea6df8..03e986ae 100644 --- a/include/spdlog/sinks/async_sink.h +++ b/include/spdlog/sinks/async_sink.h @@ -42,7 +42,7 @@ public: err_handler custom_err_handler = nullptr; }; - explicit async_sink(config async_config); + explicit async_sink(const config &async_config); // create an async_sink with one backend sink template diff --git a/src/sinks/async_sink.cpp b/src/sinks/async_sink.cpp index 9c03a12a..a3d99ea2 100644 --- a/src/sinks/async_sink.cpp +++ b/src/sinks/async_sink.cpp @@ -14,11 +14,15 @@ namespace spdlog { namespace sinks { -async_sink::async_sink(config async_config) - : config_(std::move(async_config)) { +async_sink::async_sink(const config &async_config) + : config_(async_config) { if (config_.queue_size == 0 || config_.queue_size > max_queue_size) { throw spdlog_ex("async_sink: invalid queue size"); } + if (config_.custom_err_handler) { + err_helper_.set_err_handler(config_.custom_err_handler); + } + q_ = std::make_unique(config_.queue_size); worker_thread_ = std::thread([this] { if (config_.on_thread_start) config_.on_thread_start(); diff --git a/tests/test_async.cpp b/tests/test_async.cpp index 90b163a5..74e92f17 100644 --- a/tests/test_async.cpp +++ b/tests/test_async.cpp @@ -295,3 +295,17 @@ TEST_CASE("backend_ex", "[async]") { REQUIRE_NOTHROW(logger->info("Hello message")); REQUIRE_NOTHROW(logger->flush()); } + +// test async custom error handler. trigger it using a backend exception and make sure it's called +TEST_CASE("custom_err_handler", "[async]") { + bool error_called = false; + auto test_sink = std::make_shared(); + test_sink->set_exception(std::runtime_error("test backend exception")); + async_sink::config config; + config.sinks.push_back(std::move(test_sink)); + config.custom_err_handler = [&error_called](const std::string &) { error_called = true;}; + auto asink = std::make_shared(config); + spdlog::logger ("async_logger", std::move(asink)).info("Test"); + // lvalue logger so will be destructed here already so all messages were processed + REQUIRE(error_called); +}