Skip to content

Commit c90a9e8

Browse files
committed
Add log rotation
1 parent a2b5f4b commit c90a9e8

File tree

1 file changed

+38
-8
lines changed

1 file changed

+38
-8
lines changed

Source/XTool/xerrhand.cpp

+38-8
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ static const char *defprefix = "XHANDLER INFORM";
3737
static const char *exceptMSG = "EXCEPTION OCCURED";
3838
static const char *rterrorMSG = "RUN-TIME ERROR";
3939

40+
const static int MAX_LOGS = 3;
41+
4042
XErrorHandler ErrH;
4143

4244
void setSignalHandler(sighandler signalHandler) {
@@ -206,18 +208,46 @@ XErrorHandler::XErrorHandler() {
206208
crash_func = nullptr;
207209
restore_func = nullptr;
208210
state = 0;
211+
std::string pref_path;
209212
log_path.clear();
210-
const char* lop_path_ptr = GET_PREF_PATH();
211-
if (lop_path_ptr) {
212-
log_path = lop_path_ptr;
213-
SDL_free((void*) lop_path_ptr);
213+
const char* pref_path_ptr = GET_PREF_PATH();
214+
if (pref_path_ptr) {
215+
pref_path = pref_path_ptr;
216+
SDL_free((void*) pref_path_ptr);
214217
}
215-
log_path += "logfile.txt";
216-
if (std::filesystem::exists(std::filesystem::u8path(log_path))) {
218+
log_path = pref_path + "logfile.txt";
219+
//Do log rotation from oldest to current
220+
for (int i = MAX_LOGS; 0 <= i; --i) {
217221
std::error_code error;
218-
std::filesystem::remove(std::filesystem::u8path(log_path), error);
222+
std::filesystem::path src_path = std::filesystem::u8path(
223+
i == 0 ? log_path : pref_path + "logfile_" + std::to_string(i) + ".txt"
224+
);
225+
if (!std::filesystem::exists(src_path)) {
226+
continue;
227+
}
228+
if (i == MAX_LOGS) {
229+
//Oldest log, remove it
230+
std::filesystem::remove(src_path, error);
231+
if (error) {
232+
fprintf(stderr, "Error deleting oldest log file: %d %s at %s\n",
233+
error.value(), error.message().c_str(), src_path.c_str());
234+
}
235+
continue;
236+
}
237+
std::filesystem::path dst_path = std::filesystem::u8path(
238+
pref_path + "logfile_" + std::to_string(i + 1) + ".txt"
239+
);
240+
if (std::filesystem::exists(dst_path)) {
241+
std::filesystem::remove(dst_path, error);
242+
if (error) {
243+
fprintf(stderr, "Error deleting log file: %d %s at %s\n",
244+
error.value(), error.message().c_str(), dst_path.c_str());
245+
}
246+
}
247+
std::filesystem::rename(src_path, dst_path, error);
219248
if (error) {
220-
fprintf(stderr, "Error deleting log file: %d %s at %s\n", error.value(), error.message().c_str(), log_path.c_str());
249+
fprintf(stderr, "Error renaming log file: %d %s at %s\n",
250+
error.value(), error.message().c_str(), src_path.c_str());
221251
}
222252
}
223253

0 commit comments

Comments
 (0)