spdlog/tests/test_errors.cpp

58 lines
2.3 KiB
C++
Raw Normal View History

2016-08-05 08:56:40 +08:00
/*
* This content is released under the MIT License as specified in
2023-10-01 17:20:48 +08:00
* https://raw.githubusercontent.com/gabime/spdlog/v2.x/LICENSE
2023-06-07 18:23:44 +08:00
*/
2018-03-09 21:26:33 +08:00
#include <iostream>
2016-08-05 08:56:40 +08:00
2023-09-29 05:20:26 +08:00
#include "includes.h"
2023-09-29 05:45:09 +08:00
#include "spdlog/sinks/basic_file_sink.h"
2023-09-29 05:20:26 +08:00
#define SIMPLE_LOG "test_logs/simple_log.txt"
#define SIMPLE_ASYNC_LOG "test_logs/simple_async_log.txt"
2024-12-07 01:21:42 +08:00
class failing_sink final : public spdlog::sinks::base_sink<std::mutex> {
protected:
2024-01-14 00:20:08 +08:00
void sink_it_(const spdlog::details::log_msg &) final { throw std::runtime_error("some error happened during log"); }
2017-03-28 07:08:18 +08:00
void flush_() final { throw std::runtime_error("some error happened during flush"); }
};
struct custom_ex {};
2024-12-07 06:52:27 +08:00
using namespace spdlog::sinks;
TEST_CASE("default_error_handler", "[errors]") {
2023-06-07 18:23:44 +08:00
prepare_logdir();
spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_LOG);
2024-12-07 06:52:27 +08:00
auto logger = spdlog::create<basic_file_sink_mt>("test-error", filename);
2023-06-07 18:23:44 +08:00
logger->set_pattern("%v");
logger->info(SPDLOG_FMT_RUNTIME("Test message {} {}"), 1);
2023-06-07 18:23:44 +08:00
logger->info("Test message {}", 2);
logger->flush();
using spdlog::details::os::default_eol;
REQUIRE(file_contents(SIMPLE_LOG) == spdlog::fmt_lib::format("Test message 2{}", default_eol));
REQUIRE(count_lines(SIMPLE_LOG) == 1);
2016-08-05 08:56:40 +08:00
}
TEST_CASE("custom_error_handler", "[errors]") {
2023-06-07 18:23:44 +08:00
prepare_logdir();
spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_LOG);
2024-12-07 06:52:27 +08:00
auto logger = spdlog::create<basic_file_sink_mt>("test-error", filename);
logger->flush_on(spdlog::level::info);
2023-06-07 18:23:44 +08:00
logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
logger->info("Good message #1");
REQUIRE_THROWS_AS(logger->info(SPDLOG_FMT_RUNTIME("Bad format msg {} {}"), "xxx"), custom_ex);
2023-06-07 18:23:44 +08:00
logger->info("Good message #2");
require_message_count(SIMPLE_LOG, 2);
}
TEST_CASE("default_error_handler2", "[errors]") {
2024-12-07 01:21:42 +08:00
auto logger = std::make_shared<spdlog::logger>("failed_logger", std::make_shared<failing_sink>());
2023-06-07 18:23:44 +08:00
logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex);
2016-08-05 08:56:40 +08:00
}
TEST_CASE("flush_error_handler", "[errors]") {
2023-06-07 18:23:44 +08:00
auto logger = spdlog::create<failing_sink>("failed_logger");
logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
REQUIRE_THROWS_AS(logger->flush(), custom_ex);
}