在 Linux 下采集 Node.js 日志,常见做法可以分成 应用内日志规范 + 系统级采集 + 集中式收集 三块。下面按“从简单到生产级”给你一个清晰方案。
console.log 直接乱打推荐用日志库:
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' })
]
});
logger.info('server started');
✅ 好处:
Node.js 写文件:
/var/log/myapp/combined.log
用 Linux 工具看:
tail -f /var/log/myapp/combined.log
适合:
如果你用 systemd 启 Node.js:
[Unit]
Description=Node App
[Service]
ExecStart=/usr/bin/node /opt/myapp/app.js
WorkingDirectory=/opt/myapp
Restart=always
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
查看日志:
journalctl -u myapp -f
✅ 优点:
Node.js → 日志文件 → Filebeat → Kafka/Logstash → Elasticsearch → Kibana
filebeat.inputs:
- type: log
paths:
- /var/log/myapp/*.log
output.elasticsearch:
hosts: ["http://localhost:9200"]
✅ 适合:
scrape_configs:
- job_name: nodejs
static_configs:
- targets: [localhost]
labels:
job: nodejs
__path__: /var/log/myapp/*.log
配合 Grafana 看日志,很香。
docker logs -f container_id
kubectl logs -f pod-name
日志统一走 stdout,由采集组件处理。
✅ 生产环境:
traceId✅ 不推荐:
你可以告诉我:
我可以直接给你 完整配置模板。