daily_file_sink.h 9.2 KB

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