import { readdirSync, statSync, unlinkSync, truncateSync } from "fs"; import { resolve } from "path"; const LOG_DIR = resolve(import.meta.dirname || new URL(".", import.meta.url).pathname, "..", "logs"); const MAX_AGE_DAYS = 7; const MAX_SIZE_BYTES = 10 * 1024 * 1024; // 10MB function cleanup() { console.log(`[cleanup-logs] Scanning ${LOG_DIR}...`); let files; try { files = readdirSync(LOG_DIR); } catch { console.log("[cleanup-logs] Log directory not found, skipping."); return; } const now = Date.now(); const maxAge = MAX_AGE_DAYS * 24 * 60 * 60 * 1000; let deleted = 0; let truncated = 0; for (const file of files) { if (!file.endsWith(".log")) continue; const filePath = resolve(LOG_DIR, file); try { const stat = statSync(filePath); const age = now - stat.mtimeMs; if (age > maxAge && file !== "cron.log") { unlinkSync(filePath); deleted++; console.log(` 🗑️ Deleted ${file} (age: ${(age / 86400000).toFixed(1)}d)`); } else if (stat.size > MAX_SIZE_BYTES) { truncateSync(filePath, MAX_SIZE_BYTES / 2); truncated++; console.log(` ✂️ Truncated ${file} (${(stat.size / 1024 / 1024).toFixed(1)}MB → ${(MAX_SIZE_BYTES / 2 / 1024 / 1024).toFixed(1)}MB)`); } } catch (e) { console.warn(` ⚠️ Error processing ${file}: ${e.message}`); } } console.log(`[cleanup-logs] Done. Deleted: ${deleted}, Truncated: ${truncated}`); } cleanup();