Skip to content

Commit bc2eed7

Browse files
committed
Added custom error handler support to async sink
1 parent b46b6dc commit bc2eed7

File tree

4 files changed

+23
-6
lines changed

4 files changed

+23
-6
lines changed

include/spdlog/details/err_helper.h

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,5 @@ class SPDLOG_API err_helper {
1818
void handle_unknown_ex(const std::string& origin, const source_loc& loc) const noexcept;
1919
void set_err_handler(err_handler handler);
2020
};
21-
22-
23-
}} // namespace spdlog::details
21+
} // namespace details
22+
} // namespace spdlog

include/spdlog/sinks/async_sink.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class SPDLOG_API async_sink final : public sink {
4242
err_handler custom_err_handler = nullptr;
4343
};
4444

45-
explicit async_sink(config async_config);
45+
explicit async_sink(const config &async_config);
4646

4747
// create an async_sink with one backend sink
4848
template <typename Sink, typename... SinkArgs>

src/sinks/async_sink.cpp

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,15 @@
1414
namespace spdlog {
1515
namespace sinks {
1616

17-
async_sink::async_sink(config async_config)
18-
: config_(std::move(async_config)) {
17+
async_sink::async_sink(const config &async_config)
18+
: config_(async_config) {
1919
if (config_.queue_size == 0 || config_.queue_size > max_queue_size) {
2020
throw spdlog_ex("async_sink: invalid queue size");
2121
}
22+
if (config_.custom_err_handler) {
23+
err_helper_.set_err_handler(config_.custom_err_handler);
24+
}
25+
2226
q_ = std::make_unique<queue_t>(config_.queue_size);
2327
worker_thread_ = std::thread([this] {
2428
if (config_.on_thread_start) config_.on_thread_start();

tests/test_async.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,3 +295,17 @@ TEST_CASE("backend_ex", "[async]") {
295295
REQUIRE_NOTHROW(logger->info("Hello message"));
296296
REQUIRE_NOTHROW(logger->flush());
297297
}
298+
299+
// test async custom error handler. trigger it using a backend exception and make sure it's called
300+
TEST_CASE("custom_err_handler", "[async]") {
301+
bool error_called = false;
302+
auto test_sink = std::make_shared<test_sink_mt>();
303+
test_sink->set_exception(std::runtime_error("test backend exception"));
304+
async_sink::config config;
305+
config.sinks.push_back(std::move(test_sink));
306+
config.custom_err_handler = [&error_called](const std::string &) { error_called = true;};
307+
auto asink = std::make_shared<async_sink>(config);
308+
spdlog::logger ("async_logger", std::move(asink)).info("Test");
309+
// lvalue logger so will be destructed here already so all messages were processed
310+
REQUIRE(error_called);
311+
}

0 commit comments

Comments
 (0)