要清理Node.js过期日志,你可以使用一些第三方库,例如logrotate
,或者编写自定义脚本来实现。下面是两种方法的详细说明:
方法一:使用logrotate
对于Debian/Ubuntu系统,可以使用以下命令安装:
sudo apt-get install logrotate
对于RHEL/CentOS系统,可以使用以下命令安装:
sudo yum install logrotate
/etc/logrotate.d/nodejs
,并添加以下内容:/path/to/your/nodejs/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
create 0640 root adm
}
这里的配置表示每天轮转日志文件,保留最近7天的日志,压缩旧日志,如果日志文件丢失则不报错,如果日志文件为空则不轮转,创建新的日志文件时设置权限为0640,属主为root,属组为adm。
sudo logrotate -f /etc/logrotate.d/nodejs
方法二:编写自定义脚本
你可以编写一个简单的Node.js脚本来清理过期日志。以下是一个示例脚本:
const fs = require('fs');
const path = require('path');
const logsDir = '/path/to/your/nodejs/logs';
const maxDays = 7;
fs.readdir(logsDir, (err, files) => {
if (err) {
console.error('Error reading logs directory:', err);
return;
}
const now = new Date();
files.forEach(file => {
const filePath = path.join(logsDir, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error('Error reading log file stats:', err);
return;
}
const ageInDays = Math.floor((now - stats.mtime) / (1000 * 3600 * 24));
if (ageInDays > maxDays) {
fs.unlink(filePath, err => {
if (err) {
console.error('Error deleting log file:', err);
} else {
console.log(`Deleted expired log file: ${filePath}`);
}
});
}
});
});
});
将此脚本保存为clean-old-logs.js
,然后在命令行中运行node clean-old-logs.js
。你可以将此脚本添加到cron作业中,以便定期清理过期日志。
注意:在运行这些脚本之前,请确保将/path/to/your/nodejs/logs
替换为你的实际日志文件路径。