1. 使用系統原生命令實時查看日志
Ubuntu系統自帶的基礎命令可快速監控Node.js日志文件(如app.log
)的實時更新:
tail -f
:實時顯示日志文件末尾新增內容,是最常用的實時查看工具。例如tail -f /var/log/nodejs/app.log
,按Ctrl+C
退出。less
+ 跟蹤:用less app.log
打開日志文件,輸入Shift+F
進入跟蹤模式,實時查看新增內容;按Ctrl+C
退出跟蹤,q
退出less。grep
過濾:結合grep
篩選特定關鍵詞(如錯誤信息),例如tail -f app.log | grep "ERROR"
,僅顯示包含“ERROR”的日志行。2. 利用PM2進程管理器監控
PM2是Node.js應用的生產級進程管理工具,內置強大的日志管理功能:
npm install pm2 -g
pm2 start app.js --name "my-node-app" --log /var/log/nodejs/app.log
pm2 logs
命令查看所有應用的實時日志;若需查看特定應用,用pm2 logs my-node-app
;添加--lines 100
可顯示最近100行日志。pm2 install pm2-logrotate
安裝日志輪換插件,避免日志文件過大,自動切割并壓縮舊日志。3. 采用Winston/Bunyan等日志庫增強記錄
Winston和Bunyan是Node.js生態中流行的日志庫,提供靈活的日志級別、多傳輸方式和結構化日志:
winston
及winston-daily-rotate-file
(日志每日輪換),配置文件輸出、控制臺輸出和錯誤日志分離:const winston = require('winston');
const { DailyRotateFile } = require('winston-daily-rotate-file');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console({ format: winston.format.simple() }), // 控制臺輸出
new DailyRotateFile({
filename: '/var/log/nodejs/app-%DATE%.log', // 按日期分割日志文件
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d'
}),
new DailyRotateFile({
filename: '/var/log/nodejs/error-%DATE%.log',
datePattern: 'YYYY-MM-DD',
level: 'error', // 僅記錄錯誤日志
maxSize: '20m',
maxFiles: '30d'
})
]
});
logger.info('Application started on port 3000');
logger.error('Database connection failed');
4. 部署ELK Stack集中式日志管理
ELK(Elasticsearch+Logstash+Kibana)是開源的集中式日志管理方案,適合大規模應用:
sudo apt install elasticsearch kibana
,啟動服務并配置訪問權限。winston-logstash
庫,示例代碼:const winston = require('winston');
const LogstashTransport = require('winston-logstash').Logstash;
const logger = winston.createLogger({
transports: [
new LogstashTransport({
host: 'localhost',
port: 5044,
node_name: 'nodejs-app'
})
]
});
logstash-*
),通過Dashboard可視化日志指標(如請求次數、錯誤率)。5. 結合Prometheus+Grafana監控指標
若需監控應用性能指標(如請求延遲、內存使用),可使用Prometheus收集指標,Grafana可視化:
npm install prom-client
,在Node.js應用中定義指標(如HTTP請求計數、延遲直方圖):const promClient = require('prom-client');
const httpRequestDuration = new promClient.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route'],
buckets: [0.1, 0.5, 1, 2, 5] // 定義延遲桶
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
httpRequestDuration.observe(
{ method: req.method, route: req.route ? req.route.path : req.path },
(Date.now() - start) / 1000
);
});
next();
});
// 暴露/metrics端點,供Prometheus抓取
app.get('/metrics', async (req, res) => {
res.set('Content-Type', promClient.register.contentType);
res.end(await promClient.register.metrics());
});
prometheus.yml
添加Node.js應用的/metrics
端點作為抓取目標。6. 使用Log.io實時日志流
Log.io是基于Web的實時日志監控工具,支持多服務器日志集中查看:
npm install -g log.io-server log.io-file-input
。log.io-server/config.js
,添加Node.js日志文件路徑(如/var/log/nodejs/app.log
)。logio-server
(服務器),logio-file-input
(文件監控),通過瀏覽器訪問http://server-ip:6688
查看實時日志流。