7 #ifndef IFM3D_COMMON_LOGGING_LOG_WRITER_FILE_H
8 #define IFM3D_COMMON_LOGGING_LOG_WRITER_FILE_H
14 #include <fmt/color.h>
16 #include <ifm3d/common/logging/log_writer.h>
20 template <
class Formatter>
27 : max_size_(max_size),
28 keep_files_(keep_files)
30 this->SetFileName(file_name);
34 SetFileName(
const std::string& file_name)
36 const std::lock_guard<std::mutex> lock(this->mutex_);
40 size_t idx_ext = file_name.find_last_of(
".");
41 if (idx_ext != std::string::npos)
43 this->file_stem_ = file_name.substr(0, idx_ext);
44 this->file_ext_ = file_name.substr(idx_ext);
48 this->file_stem_ = file_name;
54 SetKeepFiles(
int keep_files)
56 this->keep_files_ = keep_files;
60 SetMaxSize(
size_t max_size)
62 this->max_size_ = max_size;
66 Write(
const LogEntry& entry)
override
68 const auto str = Formatter::format(entry);
70 const std::lock_guard<std::mutex> lock(this->mutex_);
72 if (!this->file_.is_open())
77 if (this->keep_files_ > 0 && this->max_size_ > 0 &&
78 this->file_size_ > this->max_size_)
83 this->file_.write(str.c_str(), str.size());
84 this->file_size_ += str.size();
87 this->file_.write(
"\r\n", 2);
88 this->file_size_ += 2;
90 this->file_.write(
"\n", 1);
91 this->file_size_ += 1;
101 auto file_name = this->GenerateFileName(0);
102 this->file_.open(file_name, std::ios::binary | std::ios::app);
105 this->file_.seekp(0, std::ios::beg);
106 auto start = this->file_.tellp();
107 this->file_.seekp(0, std::ios::end);
108 this->file_size_ = this->file_.tellp() - start;
112 this->file_size_ = 0;
120 if (
this - file_.is_open())
131 std::remove(this->GenerateFileName(this->keep_files_ - 1).c_str());
133 for (
int i = this->keep_files_ - 2; i >= 0; --i)
135 auto cur = this->GenerateFileName(i);
136 auto next = this->GenerateFileName(i + 1);
138 std::rename(cur.c_str(), next.c_str());
145 GenerateFileName(
size_t number)
148 fmt::format(
"{}.{}{}",
152 fmt::format(
"{}{}", this->file_stem_, this->file_ext_);
157 std::string file_stem_;
158 std::string file_ext_;
166 #endif // IFM3D_COMMON_LOGGING_LOG_WRITER_FILE_H