You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

186 line
5.7KB

  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/synchronous_factory.h"
  11. #include <chrono>
  12. #include <cstdio>
  13. #include <ctime>
  14. #include <mutex>
  15. #include <string>
  16. namespace spdlog {
  17. namespace sinks {
  18. /*
  19. * Generator of daily log file names in format basename.YYYY-MM-DD.ext
  20. */
  21. struct daily_filename_calculator
  22. {
  23. // Create filename for the form basename.YYYY-MM-DD
  24. static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
  25. {
  26. filename_t basename, ext;
  27. std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
  28. return fmt::format(
  29. SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}"), basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, ext);
  30. }
  31. };
  32. /*
  33. * Rotating file sink based on date.
  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 = daily_filename_calculator>
  38. class daily_file_sink final : public base_sink<Mutex>
  39. {
  40. public:
  41. // create daily file sink which rotates on given time
  42. daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute, bool truncate = false, uint16_t max_files = 0)
  43. : base_filename_(std::move(base_filename))
  44. , rotation_h_(rotation_hour)
  45. , rotation_m_(rotation_minute)
  46. , truncate_(truncate)
  47. , max_files_(max_files)
  48. , filenames_q_()
  49. {
  50. if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59)
  51. {
  52. SPDLOG_THROW(spdlog_ex("daily_file_sink: Invalid rotation time in ctor"));
  53. }
  54. auto now = log_clock::now();
  55. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
  56. file_helper_.open(filename, truncate_);
  57. rotation_tp_ = next_rotation_tp_();
  58. if (max_files_ > 0)
  59. {
  60. filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
  61. filenames_q_.push_back(std::move(filename));
  62. }
  63. }
  64. const filename_t &filename() const
  65. {
  66. return file_helper_.filename();
  67. }
  68. protected:
  69. void sink_it_(const details::log_msg &msg) override
  70. {
  71. #ifdef SPDLOG_NO_DATETIME
  72. auto time = log_clock::now();
  73. #else
  74. auto time = msg.time;
  75. #endif
  76. bool should_rotate = time >= rotation_tp_;
  77. if (should_rotate)
  78. {
  79. auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
  80. file_helper_.open(filename, truncate_);
  81. rotation_tp_ = next_rotation_tp_();
  82. }
  83. memory_buf_t formatted;
  84. base_sink<Mutex>::formatter_->format(msg, formatted);
  85. file_helper_.write(formatted);
  86. // Do the cleaning ony 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. tm now_tm(log_clock::time_point tp)
  98. {
  99. time_t tnow = log_clock::to_time_t(tp);
  100. return spdlog::details::os::localtime(tnow);
  101. }
  102. log_clock::time_point next_rotation_tp_()
  103. {
  104. auto now = log_clock::now();
  105. tm date = now_tm(now);
  106. date.tm_hour = rotation_h_;
  107. date.tm_min = rotation_m_;
  108. date.tm_sec = 0;
  109. auto rotation_time = log_clock::from_time_t(std::mktime(&date));
  110. if (rotation_time > now)
  111. {
  112. return rotation_time;
  113. }
  114. return {rotation_time + std::chrono::hours(24)};
  115. }
  116. // Delete the file N rotations ago.
  117. // Throw spdlog_ex on failure to delete the old file.
  118. void delete_old_()
  119. {
  120. using details::os::filename_to_str;
  121. using details::os::remove_if_exists;
  122. filename_t current_file = filename();
  123. if (filenames_q_.full())
  124. {
  125. auto old_filename = std::move(filenames_q_.front());
  126. filenames_q_.pop_front();
  127. bool ok = remove_if_exists(old_filename) == 0;
  128. if (!ok)
  129. {
  130. filenames_q_.push_back(std::move(current_file));
  131. SPDLOG_THROW(spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno));
  132. }
  133. }
  134. filenames_q_.push_back(std::move(current_file));
  135. }
  136. filename_t base_filename_;
  137. int rotation_h_;
  138. int rotation_m_;
  139. log_clock::time_point rotation_tp_;
  140. details::file_helper file_helper_;
  141. bool truncate_;
  142. uint16_t max_files_;
  143. details::circular_q<filename_t> filenames_q_;
  144. };
  145. using daily_file_sink_mt = daily_file_sink<std::mutex>;
  146. using daily_file_sink_st = daily_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> daily_logger_mt(
  153. const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false)
  154. {
  155. return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate);
  156. }
  157. template<typename Factory = spdlog::synchronous_factory>
  158. inline std::shared_ptr<logger> daily_logger_st(
  159. const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false)
  160. {
  161. return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate);
  162. }
  163. } // namespace spdlog