CentOS中Node.js日志如何管理
小樊
42
2025-11-27 18:18:06
CentOS 上 Node.js 日志管理实践
一 日志采集与输出
使用结构化日志库:优先选择 Winston、Pino、Bunyan、Log4js ,便于设置日志级别 (如 DEBUG、INFO、WARN、ERROR )与输出格式(如 JSON ),利于检索与分析。
输出目标:同时输出到控制台 与文件 ,错误与业务日志分文件管理,示例(Winston):
安装:npm install winston
配置:
const winston = require(‘winston’);
const logger = winston.createLogger({ level: ‘info’, format: winston.format.json(), transports: [ new winston.transports.File({ filename: ‘error.log’, level: ‘error’ }), new winston.transports.File({ filename: ‘combined.log’ }), new winston.transports.Console() ] });
运行方式:
直接运行并重定向:node app.js > logs/app.log 2>&1
使用 PM2 :pm2 start app.js --name my-app,日志命令:pm2 logs my-app
系统服务日志:若以 systemd 管理,可用 journalctl -u your-nodejs-service-name -t <tag> 查看服务日志。
二 日志轮转策略
应用内轮转(推荐与系统配合):使用 winston-daily-rotate-file 或 pino-rotate 按时间/大小 切分,支持压缩 与保留天数 。示例(Winston):
安装:npm install winston winston-daily-rotate-file
配置:
const DailyRotateFile = require(‘winston-daily-rotate-file’);
const transport = new DailyRotateFile({ filename: ‘logs/myapp.log’, datePattern: ‘.yyyy-MM-dd’, zippedArchive: true, maxFiles: ‘14’ });
const logger = winston.createLogger({ level: ‘info’, transports: [transport] });
系统级轮转:使用 logrotate 管理 Node.js 日志文件,适合与多种运行方式(直接运行、PM2、容器)兼容。示例配置 /etc/logrotate.d/nodejs_app :
/path/to/your/nodejs/app/logs/*.log { daily rotate 7 compress missingok notifempty create 0640 root root }
测试:sudo logrotate -f /etc/logrotate.d/nodejs_app
PM2 内置轮转:启用插件并配置策略
安装:pm2 install pm2-logrotate
配置:pm2 set pm2-logrotate:max_size 10M、pm2 set pm2-logrotate:retain 7、pm2 set pm2-logrotate:compress true、pm2 set pm2-logrotate:rotateInterval "0 0 * * *"
策略要点:按大小 或日期 切分;启用压缩 ;设置保留天数 ;必要时使用 copytruncate 避免应用重开文件句柄(权衡一致性)。
三 集中式日志与远程输出
使用 rsyslog 转发到远程服务器:
安装:sudo yum install rsyslog
配置(启用 UDP 514):在 /etc/rsyslog.conf 取消注释 module(load="imudp") 与 input(type="imudp" port="514"),并添加 *.* @remote_server_ip:514
重启:sudo systemctl restart rsyslog
应用侧(Winston Syslog):new winston.transports.Syslog({ host: 'remote_server_ip', port: 514, protocol: 'udp4' })
使用 Logstash/Fluentd/Elasticsearch/Kibana(ELK) 构建集中式平台,便于收集、存储、分析与可视化 日志。
四 查看与维护命令
实时查看:
PM2:pm2 logs my-app
系统服务:journalctl -u your-nodejs-service-name -f
文件:tail -f logs/app.log
检索与分析:grep 'ERROR' logs/*.log、awk '{print $1,$4}' logs/combined.log | sort | uniq -c
轮转验证:sudo logrotate -f /etc/logrotate.d/nodejs_app
目录规范:将日志统一到 /var/log/yourapp/ ,便于权限与备份管理。
五 最佳实践
采用结构化日志(JSON) ,统一时间戳 与字段 (如 level、msg、trace_id ),便于检索与聚合。
合理设置日志级别 :生产以 INFO/WARN/ERROR 为主,调试时临时开启 DEBUG 。
明确保留周期 与存储配额 ,对历史日志做压缩归档 与异地备份 。
避免在生产频繁 console.log ,使用异步与批量写入降低性能影响。
将日志目录纳入监控与告警 (如磁盘使用率阈值),并定期审计与清理 。