hourly_file_sink.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. remove_init_file_ = file_helper_.size() == 0;
  55. rotation_tp_ = next_rotation_tp_();
  56. if (max_files_ > 0)
  57. {
  58. init_filenames_q_();
  59. }
  60. }
  61. filename_t filename()
  62. {
  63. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  64. return file_helper_.filename();
  65. }
  66. protected:
  67. void sink_it_(const details::log_msg &msg) override
  68. {
  69. auto time = msg.time;
  70. bool should_rotate = time >= rotation_tp_;
  71. if (should_rotate)
  72. {
  73. if (remove_init_file_)
  74. {
  75. file_helper_.close();
  76. details::os::remove(file_helper_.filename());
  77. }
  78. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
  79. file_helper_.open(filename, truncate_);
  80. rotation_tp_ = next_rotation_tp_();
  81. }
  82. remove_init_file_ = false;
  83. memory_buf_t formatted;
  84. base_sink<Mutex>::formatter_->format(msg, formatted);
  85. file_helper_.write(formatted);
  86. // Do the cleaning only at the end because it might throw on failure.
  87. if (should_rotate && max_files_ > 0)
  88. {
  89. delete_old_();
  90. }
  91. }
  92. void flush_() override
  93. {
  94. file_helper_.flush();
  95. }
  96. private:
  97. void init_filenames_q_()
  98. {
  99. using details::os::path_exists;
  100. filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
  101. std::vector<filename_t> filenames;
  102. auto now = log_clock::now();
  103. while (filenames.size() < max_files_)
  104. {
  105. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
  106. if (!path_exists(filename))
  107. {
  108. break;
  109. }
  110. filenames.emplace_back(filename);
  111. now -= std::chrono::hours(1);
  112. }
  113. for (auto iter = filenames.rbegin(); iter != filenames.rend(); ++iter)
  114. {
  115. filenames_q_.push_back(std::move(*iter));
  116. }
  117. }
  118. tm now_tm(log_clock::time_point tp)
  119. {
  120. time_t tnow = log_clock::to_time_t(tp);
  121. return spdlog::details::os::localtime(tnow);
  122. }
  123. log_clock::time_point next_rotation_tp_()
  124. {
  125. auto now = log_clock::now();
  126. tm date = now_tm(now);
  127. date.tm_min = 0;
  128. date.tm_sec = 0;
  129. auto rotation_time = log_clock::from_time_t(std::mktime(&date));
  130. if (rotation_time > now)
  131. {
  132. return rotation_time;
  133. }
  134. return {rotation_time + std::chrono::hours(1)};
  135. }
  136. // Delete the file N rotations ago.
  137. // Throw spdlog_ex on failure to delete the old file.
  138. void delete_old_()
  139. {
  140. using details::os::filename_to_str;
  141. using details::os::remove_if_exists;
  142. filename_t current_file = file_helper_.filename();
  143. if (filenames_q_.full())
  144. {
  145. auto old_filename = std::move(filenames_q_.front());
  146. filenames_q_.pop_front();
  147. bool ok = remove_if_exists(old_filename) == 0;
  148. if (!ok)
  149. {
  150. filenames_q_.push_back(std::move(current_file));
  151. SPDLOG_THROW(spdlog_ex("Failed removing hourly file " + filename_to_str(old_filename), errno));
  152. }
  153. }
  154. filenames_q_.push_back(std::move(current_file));
  155. }
  156. filename_t base_filename_;
  157. log_clock::time_point rotation_tp_;
  158. details::file_helper file_helper_;
  159. bool truncate_;
  160. uint16_t max_files_;
  161. details::circular_q<filename_t> filenames_q_;
  162. bool remove_init_file_;
  163. };
  164. using hourly_file_sink_mt = hourly_file_sink<std::mutex>;
  165. using hourly_file_sink_st = hourly_file_sink<details::null_mutex>;
  166. } // namespace sinks
  167. //
  168. // factory functions
  169. //
  170. template<typename Factory = spdlog::synchronous_factory>
  171. inline std::shared_ptr<logger> hourly_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate = false,
  172. uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
  173. {
  174. return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate, max_files, event_handlers);
  175. }
  176. template<typename Factory = spdlog::synchronous_factory>
  177. inline std::shared_ptr<logger> hourly_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate = false,
  178. uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
  179. {
  180. return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate, max_files, event_handlers);
  181. }
  182. } // namespace spdlog