hourly_file_sink.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. #pragma once
  4. #include <spdlog/common.h>
  5. #include <spdlog/details/circular_q.h>
  6. #include <spdlog/details/file_helper.h>
  7. #include <spdlog/details/null_mutex.h>
  8. #include <spdlog/details/os.h>
  9. #include <spdlog/details/synchronous_factory.h>
  10. #include <spdlog/fmt/fmt.h>
  11. #include <spdlog/sinks/base_sink.h>
  12. #include <chrono>
  13. #include <cstdio>
  14. #include <ctime>
  15. #include <mutex>
  16. #include <string>
  17. namespace spdlog {
  18. namespace sinks {
  19. /*
  20. * Generator of Hourly log file names in format basename.YYYY-MM-DD-HH.ext
  21. */
  22. struct hourly_filename_calculator {
  23. // Create filename for the form basename.YYYY-MM-DD-H
  24. static filename_t calc_filename(const filename_t &filename, const tm &now_tm) {
  25. filename_t basename, ext;
  26. std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
  27. return fmt_lib::format(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}_{:02d}{}"), basename,
  28. now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday,
  29. now_tm.tm_hour, ext);
  30. }
  31. };
  32. /*
  33. * Rotating file sink based on time.
  34. * If truncate != false , the created file will be truncated.
  35. * If max_files > 0, retain only the last max_files and delete previous.
  36. */
  37. template <typename Mutex, typename FileNameCalc = hourly_filename_calculator>
  38. class hourly_file_sink final : public base_sink<Mutex> {
  39. public:
  40. // create hourly file sink which rotates on given time
  41. hourly_file_sink(filename_t base_filename,
  42. bool truncate = false,
  43. uint16_t max_files = 0,
  44. const file_event_handlers &event_handlers = {})
  45. : base_filename_(std::move(base_filename)),
  46. file_helper_{event_handlers},
  47. truncate_(truncate),
  48. max_files_(max_files),
  49. filenames_q_() {
  50. auto now = log_clock::now();
  51. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
  52. file_helper_.open(filename, truncate_);
  53. remove_init_file_ = file_helper_.size() == 0;
  54. rotation_tp_ = next_rotation_tp_();
  55. if (max_files_ > 0) {
  56. init_filenames_q_();
  57. }
  58. }
  59. filename_t filename() {
  60. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  61. return file_helper_.filename();
  62. }
  63. protected:
  64. void sink_it_(const details::log_msg &msg) override {
  65. auto time = msg.time;
  66. bool should_rotate = time >= rotation_tp_;
  67. if (should_rotate) {
  68. if (remove_init_file_) {
  69. file_helper_.close();
  70. details::os::remove(file_helper_.filename());
  71. }
  72. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
  73. file_helper_.open(filename, truncate_);
  74. rotation_tp_ = next_rotation_tp_();
  75. }
  76. remove_init_file_ = false;
  77. memory_buf_t formatted;
  78. base_sink<Mutex>::formatter_->format(msg, formatted);
  79. file_helper_.write(formatted);
  80. // Do the cleaning only at the end because it might throw on failure.
  81. if (should_rotate && max_files_ > 0) {
  82. delete_old_();
  83. }
  84. }
  85. void flush_() override { file_helper_.flush(); }
  86. private:
  87. void init_filenames_q_() {
  88. using details::os::path_exists;
  89. filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
  90. std::vector<filename_t> filenames;
  91. auto now = log_clock::now();
  92. while (filenames.size() < max_files_) {
  93. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
  94. if (!path_exists(filename)) {
  95. break;
  96. }
  97. filenames.emplace_back(filename);
  98. now -= std::chrono::hours(1);
  99. }
  100. for (auto iter = filenames.rbegin(); iter != filenames.rend(); ++iter) {
  101. filenames_q_.push_back(std::move(*iter));
  102. }
  103. }
  104. tm now_tm(log_clock::time_point tp) {
  105. time_t tnow = log_clock::to_time_t(tp);
  106. return spdlog::details::os::localtime(tnow);
  107. }
  108. log_clock::time_point next_rotation_tp_() {
  109. auto now = log_clock::now();
  110. tm date = now_tm(now);
  111. date.tm_min = 0;
  112. date.tm_sec = 0;
  113. auto rotation_time = log_clock::from_time_t(std::mktime(&date));
  114. if (rotation_time > now) {
  115. return rotation_time;
  116. }
  117. return {rotation_time + std::chrono::hours(1)};
  118. }
  119. // Delete the file N rotations ago.
  120. // Throw spdlog_ex on failure to delete the old file.
  121. void delete_old_() {
  122. using details::os::filename_to_str;
  123. using details::os::remove_if_exists;
  124. filename_t current_file = file_helper_.filename();
  125. if (filenames_q_.full()) {
  126. auto old_filename = std::move(filenames_q_.front());
  127. filenames_q_.pop_front();
  128. bool ok = remove_if_exists(old_filename) == 0;
  129. if (!ok) {
  130. filenames_q_.push_back(std::move(current_file));
  131. SPDLOG_THROW(spdlog_ex(
  132. "Failed removing hourly file " + filename_to_str(old_filename), errno));
  133. }
  134. }
  135. filenames_q_.push_back(std::move(current_file));
  136. }
  137. filename_t base_filename_;
  138. log_clock::time_point rotation_tp_;
  139. details::file_helper file_helper_;
  140. bool truncate_;
  141. uint16_t max_files_;
  142. details::circular_q<filename_t> filenames_q_;
  143. bool remove_init_file_;
  144. };
  145. using hourly_file_sink_mt = hourly_file_sink<std::mutex>;
  146. using hourly_file_sink_st = hourly_file_sink<details::null_mutex>;
  147. } // namespace sinks
  148. //
  149. // factory functions
  150. //
  151. template <typename Factory = spdlog::synchronous_factory>
  152. inline std::shared_ptr<logger> hourly_logger_mt(const std::string &logger_name,
  153. const filename_t &filename,
  154. bool truncate = false,
  155. uint16_t max_files = 0,
  156. const file_event_handlers &event_handlers = {}) {
  157. return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate,
  158. max_files, event_handlers);
  159. }
  160. template <typename Factory = spdlog::synchronous_factory>
  161. inline std::shared_ptr<logger> hourly_logger_st(const std::string &logger_name,
  162. const filename_t &filename,
  163. bool truncate = false,
  164. uint16_t max_files = 0,
  165. const file_event_handlers &event_handlers = {}) {
  166. return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate,
  167. max_files, event_handlers);
  168. }
  169. } // namespace spdlog