在 Ubuntu 上清理 Node.js 应用程序的日志文件,可以通过以下几种方法实现:
找到日志文件的位置:
app.log、access.log 等。删除日志文件:
rm 命令删除日志文件。例如:cd /path/to/logs
rm app.log
日志轮转工具可以帮助你自动管理日志文件的大小和数量,防止日志文件过大。
安装 logrotate:
sudo apt-get update
sudo apt-get install logrotate
配置 logrotate:
logrotate 配置文件,例如 /etc/logrotate.d/nodejs。/path/to/logs/*.log {
daily
missingok
rotate 7
compress
notifempty
create 0640 root adm
}
daily:每天轮转一次日志。missingok:如果日志文件不存在,不会报错。rotate 7:保留最近 7 天的日志文件。compress:压缩旧的日志文件。notifempty:如果日志文件为空,不进行轮转。create 0640 root adm:创建新的日志文件,权限为 0640,属主为 root,属组为 adm。测试配置:
sudo logrotate -f /etc/logrotate.d/nodejs
如果你使用的是 Node.js 的日志库(如 winston、morgan 等),可以在代码中配置日志轮转。
安装 winston 和 winston-daily-rotate-file:
npm install winston winston-daily-rotate-file
配置 winston:
const winston = require('winston');
const { DailyRotateFile } = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
transport
]
});
logger.info('Hello, world!');
通过以上方法,你可以有效地管理和清理 Ubuntu 上 Node.js 应用程序的日志文件。