7 #ifndef IFM3D_COMMON_LOGGING_LOG_WRITER_FILE_H
8 #define IFM3D_COMMON_LOGGING_LOG_WRITER_FILE_H
15 #include <fmt/color.h>
17 #include <ifm3d/common/logging/log_writer.h>
21 template <
class FORMATTER>
28 : _max_size(max_size),
29 _keep_files(keep_files)
31 this->SetFileName(file_name);
35 SetFileName(
const std::string& file_name)
37 const std::lock_guard<std::mutex> lock(this->_mutex);
41 size_t idx_ext = file_name.find_last_of(
'.');
42 if (idx_ext != std::string::npos)
44 this->_file_stem = file_name.substr(0, idx_ext);
45 this->_file_ext = file_name.substr(idx_ext);
49 this->_file_stem = file_name;
55 SetKeepFiles(
int keep_files)
57 this->_keep_files = keep_files;
61 SetMaxSize(
size_t max_size)
63 this->_max_size = max_size;
67 Write(
const LogEntry& entry)
override
69 const auto str = FORMATTER::Format(entry);
71 const std::lock_guard<std::mutex> lock(this->_mutex);
73 if (!this->_file.is_open())
78 if (this->_keep_files > 0 && this->_max_size > 0 &&
79 this->_file_size > this->_max_size)
84 this->_file.write(str.c_str(), str.size());
85 this->_file_size += str.size();
88 this->_file.write(
"\r\n", 2);
89 this->_file_size += 2;
91 this->_file.write(
"\n", 1);
92 this->_file_size += 1;
100 if (!_file.is_open())
102 auto file_name = this->generate_file_name(0);
103 this->_file.open(file_name, std::ios::binary | std::ios::app);
106 this->_file.seekp(0, std::ios::beg);
107 auto start = this->_file.tellp();
108 this->_file.seekp(0, std::ios::end);
109 this->_file_size = this->_file.tellp() - start;
113 this->_file_size = 0;
121 if (this->_file.is_open())
132 std::remove(this->generate_file_name(this->_keep_files - 1).c_str());
134 for (
int i = this->_keep_files - 2; i >= 0; --i)
136 auto cur = this->generate_file_name(i);
137 auto next = this->generate_file_name(i + 1);
139 std::rename(cur.c_str(), next.c_str());
146 generate_file_name(
size_t number)
149 fmt::format(
"{}.{}{}",
153 fmt::format(
"{}{}", this->_file_stem, this->_file_ext);
158 std::string _file_stem;
159 std::string _file_ext;
167 #endif // IFM3D_COMMON_LOGGING_LOG_WRITER_FILE_H