在 Ubuntu 上监控 Node.js 日志,常见做法分为 系统级日志、应用级日志、实时查看、集中化管理 等几个层面。下面按实用程度给你一个完整方案。
console.log / console.errorwinstonpinobunyanpm2 logssystemd如果你用 PM2 管理 Node.js:
pm2 logs
pm2 logs app-name
pm2 logs --lines 100
查看错误日志:
pm2 logs --err
日志默认位置:
~/.pm2/logs/
✅ 优点
如果你把日志写入文件:
tail -f /var/log/node/app.log
只查看错误:
tail -f /var/log/node/error.log
journalctl -u node-app -f
查看最近 100 行:
journalctl -u node-app -n 100
console.log('server start');
会被 systemd 捕获。
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' })
]
});
logger.info('Server started');
logger.error('DB connection failed');
查看日志:
tail -f combined.log
docker logs -f container_id
或:
docker logs --tail 100 container_id
适合:
npm install @sentry/node
Sentry.init({ dsn: 'https://...' });
✅ 能捕获:
| 场景 | 命令 |
|---|---|
| 实时查看日志 | tail -f app.log |
| PM2 日志 | pm2 logs |
| systemd 日志 | journalctl -u service -f |
| 查看端口 | ss -lntp |
| CPU / 内存 | htop |
✅ 最佳方案
PM2 + Winston + Sentry + 日志文件
✅ 进阶
PM2 + Loki + Grafana
如果你愿意,可以告诉我:
我可以帮你定制一套 最适合你场景的 Node.js 日志监控方案。