deleteOldLogFiles method
Future<void>
deleteOldLogFiles(
)
Implementation
Future<void> deleteOldLogFiles() async {
// This Function only run if _cacheDirectoryPath is not initialize
if (_cacheDirectoryPath == null) {
await _initializeCacheDirectory(); // Call initialization if not done yet
}
final directory = Directory(_cacheDirectoryPath ?? '');
final files = await directory
.list()
.where(
(file) =>
file.path.contains(logFilePrefix) && file.path.endsWith('.txt'),
)
.toList();
final now = DateTime.now();
for (var file in files) {
final fileName = file.path.split('/').last;
// final match = RegExp(r'onelinksdk-(\d{2})-(\d{2})-(\d{4})\.txt').firstMatch(fileName);
final match = RegExp(
'${RegExp.escape(logFilePrefix)}(\\d{2})-(\\d{2})-(\\d{4})\\.txt',
).firstMatch(fileName);
if (match != null) {
final day = int.parse(match.group(1)!);
final month = int.parse(match.group(2)!);
final year = int.parse(match.group(3)!);
final fileDate = DateTime(year, month, day);
// Delete if file is older than 7 days
if (now.difference(fileDate).inDays > 7) {
await File(file.path).delete();
}
}
}
}