daily_file_sink.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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/fmt/chrono.h>
  9. #include <spdlog/sinks/base_sink.h>
  10. #include <spdlog/details/os.h>
  11. #include <spdlog/details/circular_q.h>
  12. #include <spdlog/details/synchronous_factory.h>
  13. #include <sstream>
  14. #include <iomanip>
  15. #include <chrono>
  16. #include <cstdio>
  17. #include <mutex>
  18. #include <string>
  19. namespace spdlog {
  20. namespace sinks {
  21. /*
  22. * Generator of daily log file names in format basename.YYYY-MM-DD.ext
  23. */
  24. struct daily_filename_calculator
  25. {
  26. // Create filename for the form basename.YYYY-MM-DD
  27. static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
  28. {
  29. filename_t basename, ext;
  30. std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
  31. return fmt_lib::format(SPDLOG_FMT_STRING(SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}")), basename, now_tm.tm_year + 1900,
  32. now_tm.tm_mon + 1, now_tm.tm_mday, ext);
  33. }
  34. };
  35. /*
  36. * Generator of daily log file names with strftime format.
  37. * Usages:
  38. * auto sink = std::make_shared<spdlog::sinks::daily_file_format_sink_mt>("myapp-%Y-%m-%d:%H:%M:%S.log", hour, minute);"
  39. * auto logger = spdlog::daily_logger_format_mt("loggername, "myapp-%Y-%m-%d:%X.log", hour, minute)"
  40. *
  41. */
  42. struct daily_filename_format_calculator
  43. {
  44. static filename_t calc_filename(const filename_t &file_path, const tm &now_tm)
  45. {
  46. #if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
  47. std::wstringstream stream;
  48. #else
  49. std::stringstream stream;
  50. #endif
  51. stream << std::put_time(&now_tm, file_path.c_str());
  52. return stream.str();
  53. }
  54. };
  55. /*
  56. * Rotating file sink based on date.
  57. * If truncate != false , the created file will be truncated.
  58. * If max_files > 0, retain only the last max_files and delete previous.
  59. */
  60. template<typename Mutex, typename FileNameCalc = daily_filename_calculator>
  61. class daily_file_sink final : public base_sink<Mutex>
  62. {
  63. public:
  64. // create daily file sink which rotates on given time
  65. daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute, bool truncate = false, uint16_t max_files = 0,
  66. const file_event_handlers &event_handlers = {})
  67. : base_filename_(std::move(base_filename))
  68. , rotation_h_(rotation_hour)
  69. , rotation_m_(rotation_minute)
  70. , file_helper_{event_handlers}
  71. , truncate_(truncate)
  72. , max_files_(max_files)
  73. , filenames_q_()
  74. {
  75. if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59)
  76. {
  77. throw_spdlog_ex("daily_file_sink: Invalid rotation time in ctor");
  78. }
  79. auto now = log_clock::now();
  80. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
  81. file_helper_.open(filename, truncate_);
  82. rotation_tp_ = next_rotation_tp_();
  83. if (max_files_ > 0)
  84. {
  85. init_filenames_q_();
  86. }
  87. }
  88. filename_t filename()
  89. {
  90. std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
  91. return file_helper_.filename();
  92. }
  93. protected:
  94. void sink_it_(const details::log_msg &msg) override
  95. {
  96. auto time = msg.time;
  97. bool should_rotate = time >= rotation_tp_;
  98. if (should_rotate)
  99. {
  100. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
  101. file_helper_.open(filename, truncate_);
  102. rotation_tp_ = next_rotation_tp_();
  103. }
  104. memory_buf_t formatted;
  105. base_sink<Mutex>::formatter_->format(msg, formatted);
  106. file_helper_.write(formatted);
  107. // Do the cleaning only at the end because it might throw on failure.
  108. if (should_rotate && max_files_ > 0)
  109. {
  110. delete_old_();
  111. }
  112. }
  113. void flush_() override
  114. {
  115. file_helper_.flush();
  116. }
  117. private:
  118. void init_filenames_q_()
  119. {
  120. using details::os::path_exists;
  121. filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
  122. std::vector<filename_t> filenames;
  123. auto now = log_clock::now();
  124. while (filenames.size() < max_files_)
  125. {
  126. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
  127. if (!path_exists(filename))
  128. {
  129. break;
  130. }
  131. filenames.emplace_back(filename);
  132. now -= std::chrono::hours(24);
  133. }
  134. for (auto iter = filenames.rbegin(); iter != filenames.rend(); ++iter)
  135. {
  136. filenames_q_.push_back(std::move(*iter));
  137. }
  138. }
  139. tm now_tm(log_clock::time_point tp)
  140. {
  141. time_t tnow = log_clock::to_time_t(tp);
  142. return spdlog::details::os::localtime(tnow);
  143. }
  144. log_clock::time_point next_rotation_tp_()
  145. {
  146. auto now = log_clock::now();
  147. tm date = now_tm(now);
  148. date.tm_hour = rotation_h_;
  149. date.tm_min = rotation_m_;
  150. date.tm_sec = 0;
  151. auto rotation_time = log_clock::from_time_t(std::mktime(&date));
  152. if (rotation_time > now)
  153. {
  154. return rotation_time;
  155. }
  156. return {rotation_time + std::chrono::hours(24)};
  157. }
  158. // Delete the file N rotations ago.
  159. // Throw spdlog_ex on failure to delete the old file.
  160. void delete_old_()
  161. {
  162. using details::os::filename_to_str;
  163. using details::os::remove_if_exists;
  164. filename_t current_file = file_helper_.filename();
  165. if (filenames_q_.full())
  166. {
  167. auto old_filename = std::move(filenames_q_.front());
  168. filenames_q_.pop_front();
  169. bool ok = remove_if_exists(old_filename) == 0;
  170. if (!ok)
  171. {
  172. filenames_q_.push_back(std::move(current_file));
  173. throw_spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno);
  174. }
  175. }
  176. filenames_q_.push_back(std::move(current_file));
  177. }
  178. filename_t base_filename_;
  179. int rotation_h_;
  180. int rotation_m_;
  181. log_clock::time_point rotation_tp_;
  182. details::file_helper file_helper_;
  183. bool truncate_;
  184. uint16_t max_files_;
  185. details::circular_q<filename_t> filenames_q_;
  186. };
  187. using daily_file_sink_mt = daily_file_sink<std::mutex>;
  188. using daily_file_sink_st = daily_file_sink<details::null_mutex>;
  189. using daily_file_format_sink_mt = daily_file_sink<std::mutex, daily_filename_format_calculator>;
  190. using daily_file_format_sink_st = daily_file_sink<details::null_mutex, daily_filename_format_calculator>;
  191. } // namespace sinks
  192. //
  193. // factory functions
  194. //
  195. template<typename Factory = spdlog::synchronous_factory>
  196. inline std::shared_ptr<logger> daily_logger_mt(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0,
  197. bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
  198. {
  199. return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate, max_files, event_handlers);
  200. }
  201. template<typename Factory = spdlog::synchronous_factory>
  202. inline std::shared_ptr<logger> daily_logger_format_mt(const std::string &logger_name, const filename_t &filename, int hour = 0,
  203. int minute = 0, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
  204. {
  205. return Factory::template create<sinks::daily_file_format_sink_mt>(
  206. logger_name, filename, hour, minute, truncate, max_files, event_handlers);
  207. }
  208. template<typename Factory = spdlog::synchronous_factory>
  209. inline std::shared_ptr<logger> daily_logger_st(const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0,
  210. bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
  211. {
  212. return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate, max_files, event_handlers);
  213. }
  214. template<typename Factory = spdlog::synchronous_factory>
  215. inline std::shared_ptr<logger> daily_logger_format_st(const std::string &logger_name, const filename_t &filename, int hour = 0,
  216. int minute = 0, bool truncate = false, uint16_t max_files = 0, const file_event_handlers &event_handlers = {})
  217. {
  218. return Factory::template create<sinks::daily_file_format_sink_st>(
  219. logger_name, filename, hour, minute, truncate, max_files, event_handlers);
  220. }
  221. } // namespace spdlog