hourly_file_sink.h 6.2 KB

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