在Debian系统上配置JavaScript(Node.js)日志记录策略,可按以下步骤操作:
npm install winston
npm install pino
npm install bunyan
通过代码或环境变量设置日志级别(如info、warn、error):
const winston = require('winston');
const logger = winston.createLogger({
level: 'info', // 设置默认级别
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' })
]
});
LOG_LEVEL=debug node app.js # 通过环境变量动态设置
使用winston-daily-rotate-file或系统工具logrotate管理日志文件:
const DailyRotateFile = require('winston-daily-rotate-file');
const logger = winston.createLogger({
transports: [
new DailyRotateFile({
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d'
})
]
});
/etc/logrotate.d/js-logs文件:/var/log/js/*.log {
daily
rotate 7
compress
missingok
notifempty
}
sudo apt install rsyslog
# 编辑/etc/rsyslog.conf,添加远程服务器配置
*.* @remote-server-ip:514
sudo apt install fluentd
# 编辑/etc/fluent/fluent.conf,添加日志源和输出
<source>
@type tail
path /var/log/js/*.log
</source>
<match js.**>
@type forward
server remote-server-ip
</match>
640,仅允许root和syslog用户访问。chmod 640 /var/log/js/*.log
[1,2,3,4,5,6,7,8,9,10,11]