diff --git a/include/spdlog/sinks/daily_file_sink.h b/include/spdlog/sinks/daily_file_sink.h index 40a37a71f..f796f831d 100644 --- a/include/spdlog/sinks/daily_file_sink.h +++ b/include/spdlog/sinks/daily_file_sink.h @@ -66,8 +66,7 @@ class daily_file_sink final : public base_sink if (max_files_ > 0) { - filenames_q_ = details::circular_q(static_cast(max_files_)); - filenames_q_.push_back(std::move(filename)); + init_filenames_q_(); } } @@ -104,6 +103,28 @@ class daily_file_sink final : public base_sink } private: + void init_filenames_q_() + { + using details::os::path_exists; + + filenames_q_ = details::circular_q(static_cast(max_files_)); + std::vector filenames; + auto now = log_clock::now(); + while (filenames.size() < max_files_) + { + auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now)); + if (!path_exists(filename)) + { + break; + } + filenames.emplace_back(filename); + now -= std::chrono::hours(24); + } + for (auto iter = filenames.rbegin(); iter != filenames.rend(); ++iter) { + filenames_q_.push_back(std::move(*iter)); + } + } + tm now_tm(log_clock::time_point tp) { time_t tnow = log_clock::to_time_t(tp); @@ -167,15 +188,15 @@ using daily_file_sink_st = daily_file_sink; // template inline std::shared_ptr daily_logger_mt( - const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false) + const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0) { - return Factory::template create(logger_name, filename, hour, minute, truncate); + return Factory::template create(logger_name, filename, hour, minute, truncate, max_files); } template inline std::shared_ptr daily_logger_st( - const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false) + const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0) { - return Factory::template create(logger_name, filename, hour, minute, truncate); + return Factory::template create(logger_name, filename, hour, minute, truncate, max_files); } } // namespace spdlog