diff --git a/include/spdlog/sinks/rotating_file_sink-inl.h b/include/spdlog/sinks/rotating_file_sink-inl.h index bf9351eb..8338e172 100644 --- a/include/spdlog/sinks/rotating_file_sink-inl.h +++ b/include/spdlog/sinks/rotating_file_sink-inl.h @@ -69,6 +69,12 @@ SPDLOG_INLINE filename_t rotating_file_sink::filename() { return file_helper_.filename(); } +template +SPDLOG_INLINE void rotating_file_sink::force_rotation() { + SPDLOG_TRY { rotate_(); } + SPDLOG_CATCH_STD +} + template SPDLOG_INLINE void rotating_file_sink::sink_it_(const details::log_msg &msg) { memory_buf_t formatted; diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index cd43d349..6e71e1e7 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -28,6 +28,7 @@ public: const file_event_handlers &event_handlers = {}); static filename_t calc_filename(const filename_t &filename, std::size_t index); filename_t filename(); + void force_rotation(); protected: void sink_it_(const details::log_msg &msg) override; diff --git a/tests/test_file_logging.cpp b/tests/test_file_logging.cpp index ac378b5c..559a3bd8 100644 --- a/tests/test_file_logging.cpp +++ b/tests/test_file_logging.cpp @@ -101,3 +101,22 @@ TEST_CASE("rotating_file_logger3", "[rotating_logger]") { REQUIRE_THROWS_AS(spdlog::rotating_logger_mt("logger", basename, max_size, 0), spdlog::spdlog_ex); } + +// test forced rotation of logs +TEST_CASE("rotating_file_logger4", "[rotating_logger]") { + prepare_logdir(); + size_t max_size = 1024 * 10; + auto sink = std::make_shared(ROTATING_LOG, max_size, 2); + auto logger = std::make_shared("rotating_sink_logger", sink); + + logger->info("Test message - pre-rotation"); + logger->flush(); + + sink->force_rotation(); + + logger->info("Test message - post-rotation"); + logger->flush(); + + REQUIRE(get_filesize(ROTATING_LOG) > 0); + REQUIRE(get_filesize(ROTATING_LOG ".1") > 0); +}