您的位置:首页 >怎样利用Ubuntu JS日志进行性能分析
发布于2026-04-25 阅读(0)
扫一扫,手机访问

性能优化这事儿,最怕的就是没有头绪。所以,咱们得先明确目标:核心就是围绕响应时间、吞吐量、错误率、事件循环延迟以及内存使用这几个关键指标,建立起一套完整的可观测性体系。更重要的是,要用日志把从用户请求到后端处理的整条链路给串联起来,做到问题可追溯。
思路其实很清晰,就三步走:日志先行、结构化、分层观测。
有了思路,接下来就是落地。第一步,得把日志“管”起来。
journalctl -u your-app.service 命令集中查看和检索日志,还能方便地将应用异常与系统事件(比如 OOM Killer)关联起来。日志记好了,就是一座金矿。怎么挖出有价值的性能指标?下面这几个方法是实战中总结出来的。
有时候,问题不在应用代码本身,而在它所处的环境。这时就需要系统级工具上场,进行深度联调。
理论说再多,不如一段代码。这里提供一套开箱即用的最小可行配置和命令,你可以直接复制粘贴,快速搭建起自己的日志分析体系。
// logger.js
const winston = require('winston');
const { combine, timestamp, json, errors } = winston.format;
const logger = winston.createLogger({
level: 'info',
format: combine(
timestamp(),
errors({ stack: true }),
json()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
],
exitOnError: false
});
module.exports = logger;
// 伪代码:记录开始时间
app.use((req, res, next) => {
req._start = Date.now();
res.on('finish', () => {
const durationMs = Date.now() - req._start;
logger.info('http_request', {
method: req.method,
url: req.url,
statusCode: res.statusCode,
durationMs,
userAgent: req.get('user-agent'),
ip: req.ip
});
});
next();
});
# 统计 95/99 分位响应时间(单位 ms)
tail -n 100000 app.log | \
jq -r 'select(.msg=="http_request") | .durationMs' | \
sort -n | \
awk '{a[NR]=$1; sum+=$1; if(NR==1){min=$1} else if($1max){max=$1}} END {n=NR; asort(a);p95=a[int(n*0.95)]; p99=a[int(n*0.99)];printf "count=%d min=%.2f max=%.2f mean=%.2f p95=%.2f p99=%.2f\n",n, min, max, sum/n, p95, p99}'
# 实时查看错误与慢请求
tail -f app.log | jq 'select(.level=="error" or .durationMs > 1000)'
# 按路由统计平均时延
tail -n 100000 app.log | \
jq -r 'select(.msg=="http_request") | "\(.route) \(.durationMs)"' | \
awk '{sum[$1]+=$2; cnt[$1]++} END {for(r in sum) printf "%s %.2f\n", r, sum[r]/cnt[r]}'
# 查看服务日志
journalctl -u your-app.service -f
# 资源与 I/O 快速巡检
top -b -d 1 -n 20
vmstat 1 20
iostat -x 1 20
free -m
df -h
# CPU 剖析
node --prof app.js
# 生成可读报告(Linux)
node --prof-process isolate-*.log > profile.txt
# 远程调试
node --inspect-brk app.js
# 打开 Chrome:chrome://inspect -> 连接并采集 Performance/Memory
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9