diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h index 87784f1b..ae0f70f6 100644 --- a/include/spdlog/sinks/rotating_file_sink.h +++ b/include/spdlog/sinks/rotating_file_sink.h @@ -31,13 +31,17 @@ template class rotating_file_sink final : public base_sink { public: - rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files) + rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open=false) : base_filename_(std::move(base_filename)) , max_size_(max_size) , max_files_(max_files) { file_helper_.open(calc_filename(base_filename_, 0)); current_size_ = file_helper_.size(); // expensive. called only once + if (rotate_on_open && current_size_ > 0) + { + rotate_(); + } } // calc filename according to index and file extension if exists. @@ -146,15 +150,15 @@ using rotating_file_sink_st = rotating_file_sink; template inline std::shared_ptr rotating_logger_mt( - const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files) + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files, bool rotate_on_open=false) { - return Factory::template create(logger_name, filename, max_file_size, max_files); + return Factory::template create(logger_name, filename, max_file_size, max_files, rotate_on_open); } template inline std::shared_ptr rotating_logger_st( - const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files) + const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files, bool rotate_on_open = false) { - return Factory::template create(logger_name, filename, max_file_size, max_files); + return Factory::template create(logger_name, filename, max_file_size, max_files, rotate_on_open); } } // namespace spdlog diff --git a/tests/test_file_logging.cpp b/tests/test_file_logging.cpp index c5886f5f..dd0c8999 100644 --- a/tests/test_file_logging.cpp +++ b/tests/test_file_logging.cpp @@ -60,7 +60,20 @@ TEST_CASE("rotating_file_logger2", "[rotating_logger]]") prepare_logdir(); size_t max_size = 1024 * 10; std::string basename = "logs/rotating_log"; - auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 1); + + { + // make an initial logger to create the first output file + auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 2, true); + for (int i = 0; i < 10; ++i) + { + logger->info("Test message {}", i); + } + // drop causes the logger destructor to be called, which is required so the + // next logger can rename the first output file. + spdlog::drop(logger->name()); + } + + auto logger = spdlog::rotating_logger_mt("logger", basename, max_size, 2, true); for (int i = 0; i < 10; ++i) { logger->info("Test message {}", i);