设置Node.js日志的保留策略可以通过多种方式实现,具体取决于你使用的日志库和部署环境。以下是一些常见的方法和示例:
winston
日志库winston
是一个流行的Node.js日志库,可以通过配置来实现日志的保留策略。
安装 winston
和 winston-daily-rotate-file
npm install winston winston-daily-rotate-file
配置 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
指定了保留日志文件的最大天数。morgan
和 winston
如果你使用 morgan
作为HTTP请求日志库,可以结合 winston
来实现日志的保留策略。
安装 morgan
和 winston-daily-rotate-file
npm install morgan winston winston-daily-rotate-file
配置 morgan
和 winston
const express = require('express');
const morgan = require('morgan');
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const app = express();
const transport = new DailyRotateFile({
filename: 'access-%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
]
});
app.use(morgan('combined', { stream: { write: message => logger.info(message.trim()) } }));
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
如果你不想在代码中处理日志保留策略,可以使用系统工具如 logrotate
来管理日志文件。
安装 logrotate
sudo apt-get install logrotate # Debian/Ubuntu
sudo yum install logrotate # CentOS/RHEL
配置 logrotate
创建一个 logrotate
配置文件,例如 /etc/logrotate.d/nodejs
:
/path/to/your/nodejs/logs/*.log {
daily
rotate 14
compress
delaycompress
missingok
notifempty
create 640 root adm
}
在这个配置中:
daily
表示每天轮转日志。rotate 14
表示保留14天的日志。compress
表示压缩旧的日志文件。delaycompress
表示延迟压缩,直到下一次轮转。missingok
表示如果日志文件不存在,不会报错。notifempty
表示如果日志文件为空,不进行轮转。create 640 root adm
表示创建新日志文件的权限和所有者。通过这些方法,你可以有效地管理Node.js应用程序的日志文件,确保它们不会占用过多的磁盘空间。