Skip to content

Commit

Permalink
Added custom error handler support to async sink
Browse files Browse the repository at this point in the history
  • Loading branch information
gabime committed Jan 17, 2025
1 parent b46b6dc commit bc2eed7
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 6 deletions.
5 changes: 2 additions & 3 deletions include/spdlog/details/err_helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,5 @@ class SPDLOG_API err_helper {
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
2 changes: 1 addition & 1 deletion include/spdlog/sinks/async_sink.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class SPDLOG_API async_sink final : public sink {
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 <typename Sink, typename... SinkArgs>
Expand Down
8 changes: 6 additions & 2 deletions src/sinks/async_sink.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<queue_t>(config_.queue_size);
worker_thread_ = std::thread([this] {
if (config_.on_thread_start) config_.on_thread_start();
Expand Down
14 changes: 14 additions & 0 deletions tests/test_async.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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_mt>();
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<async_sink>(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);
}

0 comments on commit bc2eed7

Please sign in to comment.