在Ubuntu系统中,Node.js应用程序的日志轮转可以通过多种方法实现。以下是一些常用的方法:
logrotate工具logrotate是Linux系统中用于管理日志文件的工具,可以自动轮转、压缩和删除旧日志文件。
安装logrotate(如果尚未安装):
sudo apt-get update
sudo apt-get install logrotate
创建或编辑logrotate配置文件:
通常,logrotate的配置文件位于/etc/logrotate.d/目录下。你可以为你的Node.js应用程序创建一个新的配置文件,例如/etc/logrotate.d/myapp。
sudo nano /etc/logrotate.d/myapp
添加配置内容: 在配置文件中添加以下内容,根据你的日志文件路径和需求进行调整:
/path/to/your/nodejs/app/logs/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 640 root adm
}
解释:
daily: 每天轮转一次日志。rotate 7: 保留7个轮转后的日志文件。compress: 压缩轮转后的日志文件。delaycompress: 延迟压缩,直到下一次轮转。missingok: 如果日志文件不存在,不会报错。notifempty: 如果日志文件为空,不进行轮转。create 640 root adm: 创建新的日志文件,权限为640,属主为root,属组为adm。测试配置:
你可以手动测试logrotate配置是否正确:
sudo logrotate -f /etc/logrotate.d/myapp
如果你使用的是Node.js的日志库(如winston、pino等),这些库通常内置了日志轮转功能。
winston示例:const winston = require('winston');
const { combine, timestamp, printf } = winston.format;
const myFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});
const logger = winston.createLogger({
format: combine(
timestamp(),
myFormat
),
transports: [
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' })
]
});
// 自动轮转日志
const DailyRotateFile = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: 'logs/application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
logger.add(transport);
logger.info('Hello, world!');
在这个示例中,winston-daily-rotate-file插件用于实现日志的每日轮转,并且可以设置日志文件的最大大小和保留天数。
通过以上方法,你可以在Ubuntu系统中有效地管理Node.js应用程序的日志文件。