You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.4 KiB
43 lines
1.4 KiB
import log4js from "logger";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
|
|
const logger = log4js.getLogger("SCHEDULER");
|
|
|
|
const LOG_DIR = path.resolve(process.cwd(), "logs");
|
|
|
|
export default async function cleanupLogs(payload?: Record<string, unknown>) {
|
|
const days = (payload?.days as number) ?? 30;
|
|
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
|
|
|
|
let deletedCount = 0;
|
|
|
|
try {
|
|
if (!fs.existsSync(LOG_DIR)) {
|
|
logger.info("Log cleanup: log dir does not exist, skipping");
|
|
return { success: true, message: "Log dir not found", deleted: 0 };
|
|
}
|
|
|
|
const files = fs.readdirSync(LOG_DIR);
|
|
for (const file of files) {
|
|
if (!file.endsWith(".log") && !file.endsWith(".log.gz")) continue;
|
|
|
|
const filePath = path.join(LOG_DIR, file);
|
|
try {
|
|
const stat = fs.statSync(filePath);
|
|
if (stat.mtimeMs < cutoff) {
|
|
fs.unlinkSync(filePath);
|
|
deletedCount++;
|
|
}
|
|
} catch {
|
|
// 单个文件删除失败不中断整体清理
|
|
}
|
|
}
|
|
|
|
logger.info("Log cleanup: removed %d files older than %d days", deletedCount, days);
|
|
return { success: true, message: `Cleaned ${deletedCount} log files older than ${days} days`, deleted: deletedCount };
|
|
} catch (err) {
|
|
logger.error("Log cleanup failed: %s", err instanceof Error ? err.message : String(err));
|
|
return { success: false, message: "Log cleanup failed", deleted: 0 };
|
|
}
|
|
}
|
|
|