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/details/file_helper.h>
7#include <spdlog/details/null_mutex.h>
8#include <spdlog/details/synchronous_factory.h>
9#include <spdlog/sinks/base_sink.h>
10
11#include <chrono>
12#include <mutex>
13#include <string>
14
15namespace spdlog {
16namespace sinks {
17
18//
19// Rotating file sink based on size
20//
21template <typename Mutex>
22class rotating_file_sink final : public base_sink<Mutex> {
23public:
24 rotating_file_sink(filename_t base_filename,
25 std::size_t max_size,
26 std::size_t max_files,
27 bool rotate_on_open = false,
28 const file_event_handlers &event_handlers = {});
29 static filename_t calc_filename(const filename_t &filename, std::size_t index);
30 filename_t filename();
31
32protected:
33 void sink_it_(const details::log_msg &msg) override;
34 void flush_() override;
35
36private:
37 // Rotate files:
38 // log.txt -> log.1.txt
39 // log.1.txt -> log.2.txt
40 // log.2.txt -> log.3.txt
41 // log.3.txt -> delete
42 void rotate_();
43
44 // delete the target if exists, and rename the src file to target
45 // return true on success, false otherwise.
46 bool rename_file_(const filename_t &src_filename, const filename_t &target_filename);
47
48 filename_t base_filename_;
49 std::size_t max_size_;
50 std::size_t max_files_;
51 std::size_t current_size_;
52 details::file_helper file_helper_;
53};
54
55using rotating_file_sink_mt = rotating_file_sink<std::mutex>;
56using rotating_file_sink_st = rotating_file_sink<details::null_mutex>;
57
58} // namespace sinks
59
60//
61// factory functions
62//
63
64template <typename Factory = spdlog::synchronous_factory>
65inline std::shared_ptr<logger> rotating_logger_mt(const std::string &logger_name,
66 const filename_t &filename,
67 size_t max_file_size,
68 size_t max_files,
69 bool rotate_on_open = false,
70 const file_event_handlers &event_handlers = {}) {
71 return Factory::template create<sinks::rotating_file_sink_mt>(
72 logger_name, filename, max_file_size, max_files, rotate_on_open, event_handlers);
73}
74
75template <typename Factory = spdlog::synchronous_factory>
76inline std::shared_ptr<logger> rotating_logger_st(const std::string &logger_name,
77 const filename_t &filename,
78 size_t max_file_size,
79 size_t max_files,
80 bool rotate_on_open = false,
81 const file_event_handlers &event_handlers = {}) {
82 return Factory::template create<sinks::rotating_file_sink_st>(
83 logger_name, filename, max_file_size, max_files, rotate_on_open, event_handlers);
84}
85} // namespace spdlog
86
87#ifdef SPDLOG_HEADER_ONLY
88 #include "rotating_file_sink-inl.h"
89#endif
90