Maximum number of log files to keep
export function cleanupOldLogs(maxFiles: number): void {
try {
if (maxFiles <= 0) return; // Skip if setting is invalid
if (!fs.existsSync(logsPath)) return; // Skip if logs directory doesn't exist
// Get all log files except the current log file
const logFiles = fs
.readdirSync(logsPath)
.filter((file) => file !== "latest.log" && file.endsWith(".log"))
.map((file) => {
const stats = fs.statSync(path.join(logsPath, file));
return { file, mtime: stats.mtime.getTime() };
})
.sort((a, b) => b.mtime - a.mtime); // Sort newest first
// If we have more files than the max, delete the oldest ones
if (logFiles.length > maxFiles) {
const filesToDelete = logFiles.slice(maxFiles);
for (const { file } of filesToDelete) {
try {
fs.unlinkSync(path.join(logsPath, file));
console.log(`Deleted old log file: ${file}`);
} catch (error) {
console.error(`Failed to delete log file ${file}:`, error);
}
}
console.log(
`Cleaned up ${filesToDelete.length} old log files, keeping ${maxFiles} most recent`,
);
}
} catch (error) {
console.error("Error cleaning up old logs:", error);
}
}
Clean up old log files based on maxLogFiles setting Keeps only the specified number of most recent log files