spdlog
Loading...
Searching...
No Matches
daily_file_sink.h
Go to the documentation of this file.
1// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
2// Distributed under the MIT License (http://opensource.org/licenses/MIT)
3
4#pragma once
5
6#include <spdlog/common.h>
9#include <spdlog/fmt/fmt.h>
10#include <spdlog/fmt/chrono.h>
12#include <spdlog/details/os.h>
15
16#include <chrono>
17#include <cstdio>
18#include <ctime>
19#include <mutex>
20#include <string>
21
22namespace spdlog {
23namespace sinks {
24
25/*
26 * Generator of daily log file names in format basename.YYYY-MM-DD.ext
27 */
29{
30 // Create filename for the form basename.YYYY-MM-DD
31 static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
32 {
33 filename_t basename, ext;
34 std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
35 return fmt::format(
36 SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}"), basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, ext);
37 }
38};
39
40/*
41 * Generator of daily log file names with strftime format.
42 * Usages:
43 * auto sink = std::make_shared<spdlog::sinks::daily_file_format_sink_mt>("myapp-%Y-%m-%d:%H:%M:%S.log", hour, minute);"
44 * auto logger = spdlog::daily_logger_format_mt("loggername, "myapp-%Y-%m-%d:%X.log", hour, minute)"
45 *
46 */
48{
49 static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
50 {
51 // generate fmt datetime format string, e.g. {:%Y-%m-%d}.
52 filename_t fmt_filename = fmt::format(SPDLOG_FILENAME_T("{{:{}}}"), filename);
53#if defined(_MSC_VER) && defined(SPDLOG_WCHAR_FILENAMES) // for some reason msvc doesnt allow fmt::runtime(..) with wchar here
54 return fmt::format(fmt_filename, now_tm);
55#else
56 return fmt::format(SPDLOG_FMT_RUNTIME(fmt_filename), now_tm);
57#endif
58 }
59};
60
61/*
62 * Rotating file sink based on date.
63 * If truncate != false , the created file will be truncated.
64 * If max_files > 0, retain only the last max_files and delete previous.
65 */
66template<typename Mutex, typename FileNameCalc = daily_filename_calculator>
67class daily_file_sink final : public base_sink<Mutex>
68{
69public:
70 // create daily file sink which rotates on given time
71 daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute, bool truncate = false, uint16_t max_files = 0)
72 : base_filename_(std::move(base_filename))
73 , rotation_h_(rotation_hour)
74 , rotation_m_(rotation_minute)
75 , truncate_(truncate)
76 , max_files_(max_files)
77 , filenames_q_()
78 {
79 if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59)
80 {
81 throw_spdlog_ex("daily_file_sink: Invalid rotation time in ctor");
82 }
83
84 auto now = log_clock::now();
85 auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
88
89 if (max_files_ > 0)
90 {
92 }
93 }
94
100
101protected:
102 void sink_it_(const details::log_msg &msg) override
103 {
104 auto time = msg.time;
105 bool should_rotate = time >= rotation_tp_;
106 if (should_rotate)
107 {
108 auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
111 }
112 memory_buf_t formatted;
113 base_sink<Mutex>::formatter_->format(msg, formatted);
114 file_helper_.write(formatted);
115
116 // Do the cleaning only at the end because it might throw on failure.
117 if (should_rotate && max_files_ > 0)
118 {
119 delete_old_();
120 }
121 }
122
123 void flush_() override
124 {
126 }
127
128private:
130 {
132
134 std::vector<filename_t> filenames;
135 auto now = log_clock::now();
136 while (filenames.size() < max_files_)
137 {
138 auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
139 if (!path_exists(filename))
140 {
141 break;
142 }
143 filenames.emplace_back(filename);
144 now -= std::chrono::hours(24);
145 }
146 for (auto iter = filenames.rbegin(); iter != filenames.rend(); ++iter)
147 {
148 filenames_q_.push_back(std::move(*iter));
149 }
150 }
151
152 tm now_tm(log_clock::time_point tp)
153 {
154 time_t tnow = log_clock::to_time_t(tp);
156 }
157
158 log_clock::time_point next_rotation_tp_()
159 {
160 auto now = log_clock::now();
161 tm date = now_tm(now);
162 date.tm_hour = rotation_h_;
163 date.tm_min = rotation_m_;
164 date.tm_sec = 0;
165 auto rotation_time = log_clock::from_time_t(std::mktime(&date));
166 if (rotation_time > now)
167 {
168 return rotation_time;
169 }
170 return {rotation_time + std::chrono::hours(24)};
171 }
172
173 // Delete the file N rotations ago.
174 // Throw spdlog_ex on failure to delete the old file.
176 {
179
180 filename_t current_file = file_helper_.filename();
181 if (filenames_q_.full())
182 {
183 auto old_filename = std::move(filenames_q_.front());
184 filenames_q_.pop_front();
185 bool ok = remove_if_exists(old_filename) == 0;
186 if (!ok)
187 {
188 filenames_q_.push_back(std::move(current_file));
189 throw_spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno);
190 }
191 }
192 filenames_q_.push_back(std::move(current_file));
193 }
194
198 log_clock::time_point rotation_tp_;
201 uint16_t max_files_;
203};
204
209
210} // namespace sinks
211
212//
213// factory functions
214//
215template<typename Factory = spdlog::synchronous_factory>
217 const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
218{
219 return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate, max_files);
220}
221
222template<typename Factory = spdlog::synchronous_factory>
224 const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
225{
226 return Factory::template create<sinks::daily_file_format_sink_mt>(logger_name, filename, hour, minute, truncate, max_files);
227}
228
229template<typename Factory = spdlog::synchronous_factory>
231 const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
232{
233 return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate, max_files);
234}
235
236template<typename Factory = spdlog::synchronous_factory>
238 const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
239{
240 return Factory::template create<sinks::daily_file_format_sink_st>(logger_name, filename, hour, minute, truncate, max_files);
241}
242} // namespace spdlog
const filename_t & filename() const
void write(const memory_buf_t &buf)
static std::tuple< filename_t, filename_t > split_by_extension(const filename_t &fname)
void open(const filename_t &fname, bool truncate=false)
log_clock::time_point rotation_tp_
log_clock::time_point next_rotation_tp_()
details::circular_q< filename_t > filenames_q_
daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute, bool truncate=false, uint16_t max_files=0)
tm now_tm(log_clock::time_point tp)
void sink_it_(const details::log_msg &msg) override
details::file_helper file_helper_
#define SPDLOG_FILENAME_T(s)
Definition common.h:107
#define SPDLOG_FMT_RUNTIME(format_string)
Definition common.h:45
T emplace_back(T... args)
T mktime(T... args)
SPDLOG_INLINE std::string filename_to_str(const filename_t &filename)
Definition os-inl.h:387
SPDLOG_INLINE int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT
Definition os-inl.h:172
SPDLOG_INLINE std::tm localtime() SPDLOG_NOEXCEPT
Definition os-inl.h:97
SPDLOG_INLINE bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT
Definition os-inl.h:187
Definition async.h:25
std::shared_ptr< logger > daily_logger_st(const std::string &logger_name, const filename_t &filename, int hour=0, int minute=0, bool truncate=false, uint16_t max_files=0)
std::shared_ptr< logger > daily_logger_format_mt(const std::string &logger_name, const filename_t &filename, int hour=0, int minute=0, bool truncate=false, uint16_t max_files=0)
std::shared_ptr< logger > daily_logger_format_st(const std::string &logger_name, const filename_t &filename, int hour=0, int minute=0, bool truncate=false, uint16_t max_files=0)
SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno)
Definition common-inl.h:68
std::shared_ptr< logger > daily_logger_mt(const std::string &logger_name, const filename_t &filename, int hour=0, int minute=0, bool truncate=false, uint16_t max_files=0)
fmt::basic_memory_buffer< char, 250 > memory_buf_t
Definition common.h:116
T rbegin(T... args)
T rend(T... args)
T size(T... args)
log_clock::time_point time
Definition log_msg.h:22
static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
T tie(T... args)