在 CentOS 上監控 Node.js 應用的性能指標可以通過以下幾種方法:
使用 watch
命令:
watch
命令可以定期執行指定的命令,實時反饋服務器狀態。例如,可以使用以下命令監控 Node.js 進程的狀態:watch -n 1 ps aux | grep node
還可以監控服務器日志文件的變化:watch -n 1 tail -f /path/to/your/server.log
使用 Systemd:
kenniu.service
:[Unit]
Description=My Node.js App
After=network.target
[Service]
ExecStart=/usr/bin/node /path/to/entry.js
Restart=always
[Install]
WantedBy=multi-user.target
然后啟動并啟用該服務:sudo systemctl start kenniu
sudo systemctl enable kenniu
sudo systemctl status kenniu
使用 journalctl
命令查看相關日志:journalctl -u kenniu -t
使用第三方監控工具:
日志管理工具:
journalctl
查看系統日志:journalctl -u your-nodejs-service-name -t
Node.js 內置模塊:
os
模塊獲取 CPU 和內存使用情況:const os = require('os');
function monitorCpuAndMemory() {
setInterval(() => {
const cpuUsage = os.cpuUsage();
const memoryInfo = os.freemem() / 1024 / 1024;
console.log(`CPU Usage: ${cpuUsage}%`);
console.log(`Memory Available: ${memoryInfo.toFixed(2)} MB`);
}, 5000);
}
monitorCpuAndMemory();
通過這些方法,可以有效地監控和管理 CentOS 上的 Node.js 應用性能指標,確保其穩定高效運行。