diff --git a/include/spdlog/sinks/basic_file_sink-inl.h b/include/spdlog/sinks/basic_file_sink-inl.h index f7c1abf7..ce0ddad0 100644 --- a/include/spdlog/sinks/basic_file_sink-inl.h +++ b/include/spdlog/sinks/basic_file_sink-inl.h @@ -26,6 +26,12 @@ SPDLOG_INLINE const filename_t &basic_file_sink::filename() const { return file_helper_.filename(); } +template +SPDLOG_INLINE void basic_file_sink::truncate() { + std::lock_guard lock(base_sink::mutex_); + file_helper_.reopen(true); +} + template SPDLOG_INLINE void basic_file_sink::sink_it_(const details::log_msg &msg) { memory_buf_t formatted; diff --git a/include/spdlog/sinks/basic_file_sink.h b/include/spdlog/sinks/basic_file_sink.h index 699caa14..48c07671 100644 --- a/include/spdlog/sinks/basic_file_sink.h +++ b/include/spdlog/sinks/basic_file_sink.h @@ -23,6 +23,7 @@ public: bool truncate = false, const file_event_handlers &event_handlers = {}); const filename_t &filename() const; + void truncate(); 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 0e4902be..71d06a6d 100644 --- a/tests/test_file_logging.cpp +++ b/tests/test_file_logging.cpp @@ -45,6 +45,26 @@ TEST_CASE("flush_on", "[flush_on]") { default_eol, default_eol, default_eol)); } +TEST_CASE("simple_file_logger", "[truncate]") { + prepare_logdir(); + const spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_LOG); + const bool truncate = true; + const auto sink = std::make_shared(filename, truncate); + const auto logger = std::make_shared("simple_file_logger", sink); + + logger->info("Test message {}", 3.14); + logger->info("Test message {}", 2.71); + logger->flush(); + REQUIRE(count_lines(SIMPLE_LOG) == 2); + + sink->truncate(); + REQUIRE(count_lines(SIMPLE_LOG) == 0); + + logger->info("Test message {}", 6.28); + logger->flush(); + REQUIRE(count_lines(SIMPLE_LOG) == 1); +} + TEST_CASE("rotating_file_logger1", "[rotating_logger]") { prepare_logdir(); size_t max_size = 1024 * 10;