在 Linux 环境下排查 Node.js(或前端 JS 服务)日志中的“慢”问题,通常可以从日志分析、系统监控、代码级定位三个层面来做。下面按实用顺序给你一套排查思路。
先明确是哪种慢:
不同场景排查方式不同。
如果你用的是常见框架:
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.url} ${Date.now() - start}ms`);
});
next();
});
重点看:
假设日志格式:
2026-01-21 10:00:01 GET /api/user 1200ms
grep "ms" app.log | sort -t' ' -kNF | tail -n 20
或:
awk '{print $NF, $0}' app.log | sort -rn | head
grep -c "500ms" app.log
top
htop
关注:
iostat -x 1
如果:
%util 高await 大说明磁盘 IO 慢(常见于日志写入、数据库)
netstat -anp | grep node
ss -tnp
或抓包:
tcpdump -i eth0 port 3306
node --prof app.js
生成:
node --prof-process isolate-*.log > profile.txt
看哪个函数耗时最多。
npm install -g clinic
clinic doctor -- node app.js
它会自动分析:
const start = Date.now();
setInterval(() => {
const delay = Date.now() - start - 1000;
if (delay > 100) console.log('event loop delay', delay);
}, 1000);
SHOW SLOW QUERY LOG;
或:
mysqldumpslow -s t /var/log/mysql/slow.log
在 Node 中:
axios.get(url, { timeout: 2000 })
并打日志:
console.log('call api cost', Date.now() - start);
如果你愿意,可以把:
发给我,我可以直接帮你分析。