在Ubuntu系统中,Node.js应用程序的日志轮转可以通过多种方式实现。以下是一些常见的方法:
logrotate工具安装logrotate(如果尚未安装):
sudo apt-get update
sudo apt-get install logrotate
创建或编辑logrotate配置文件:
通常,Node.js应用程序的日志文件位于/var/log/nodejs/目录下。你可以为这个目录创建一个logrotate配置文件。
sudo nano /etc/logrotate.d/nodejs
添加以下内容到配置文件:
/var/log/nodejs/*.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
winston和winston-daily-rotate-file如果你希望在Node.js应用程序内部处理日志轮转,可以使用winston和winston-daily-rotate-file库。
安装所需的库:
npm install winston winston-daily-rotate-file
配置winston:
在你的Node.js应用程序中,配置winston使用winston-daily-rotate-file进行日志轮转。
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!');
解释:
filename: 日志文件的名称模板。datePattern: 日期模式,用于生成日志文件名。zippedArchive: 是否压缩旧的日志文件。maxSize: 单个日志文件的最大大小。maxFiles: 保留的最大日志文件数量。通过以上两种方法,你可以有效地管理Node.js应用程序的日志轮转。选择哪种方法取决于你的具体需求和环境。