@@ -37,6 +37,8 @@ static const char *defprefix = "XHANDLER INFORM";
37
37
static const char *exceptMSG = " EXCEPTION OCCURED" ;
38
38
static const char *rterrorMSG = " RUN-TIME ERROR" ;
39
39
40
+ const static int MAX_LOGS = 3 ;
41
+
40
42
XErrorHandler ErrH;
41
43
42
44
void setSignalHandler (sighandler signalHandler) {
@@ -206,18 +208,46 @@ XErrorHandler::XErrorHandler() {
206
208
crash_func = nullptr ;
207
209
restore_func = nullptr ;
208
210
state = 0 ;
211
+ std::string pref_path;
209
212
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 );
214
217
}
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) {
217
221
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);
219
248
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 ());
221
251
}
222
252
}
223
253
0 commit comments