1. 启用结构化日志记录
结构化日志(如JSON格式)是性能分析的基础,便于后续用工具解析和聚合数据。推荐使用Winston或Pino这类高级日志库,它们支持多传输(文件、控制台)、日志级别(info/warn/error)和格式化。例如,用Winston配置JSON日志:
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('Request received', { method: 'GET', path: '/api', latency: 120 }); // 包含性能指标
2. 记录关键性能指标
在代码中埋点记录响应时间、内存使用、CPU占用等核心指标,为分析提供数据源。例如:
// 记录请求响应时间(毫秒)
const start = process.hrtime();
app.get('/api', (req, res) => {
// 业务逻辑...
const diff = process.hrtime(start);
const latency = (diff[0] * 1e9 + diff[1]) / 1e6;
logger.info('Request completed', { method: req.method, path: req.path, latency });
});
// 定期记录内存和CPU使用率
setInterval(() => {
const memory = process.memoryUsage();
const cpu = process.cpuUsage();
logger.info('System metrics', {
memoryUsage: `${memory.heapUsed / 1024 / 1024}MB`,
cpuUsage: `${(cpu.user / 1e6).toFixed(2)}ms`
});
}, 5000); // 每5秒记录一次
3. 使用命令行工具快速分析
Ubuntu的命令行工具可快速定位性能问题,适合日常排查:
grep 'ERROR' /path/to/combined.log
combined.log
中所有请求的平均延迟(假设日志中有latency
字段):awk -F'latency":' '{if($2) {sum+=$2; count++}} END {print "Average latency: " sum/count "ms"}' combined.log
grep 'ERROR' combined.log | awk -F'"message":' '{print $2}' | sort | uniq -c | sort -nr
4. 利用日志管理工具深度分析
对于大规模或分布式系统,使用ELK Stack(Elasticsearch+Logstash+Kibana)或Graylog等工具,实现日志的集中存储、可视化和高级分析:
sudo apt install elasticsearch logstash
。/etc/logstash/conf.d/nodejs.conf
):input { file { path => "/path/to/combined.log" start_position => "beginning" codec => "json" } }
filter {
grok { match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:loglevel} %{GREEDYDATA:msg}" } }
date { match => ["timestamp", "ISO8601"] }
}
output { elasticsearch { hosts => ["localhost:9200"] index => "nodejs-%{+YYYY.MM.dd}" } }
sudo systemctl start logstash
。http://localhost:5601
)创建索引模式,可视化分析日志中的性能指标(如响应时间趋势、错误率)。npm install -g pm2
pm2 start app.js --name "my-app"
pm2 logs my-app # 实时查看日志
pm2 monit # 监控CPU、内存使用
5. 日志轮转避免文件过大
使用Logrotate工具定期分割、压缩日志文件,防止磁盘空间耗尽。创建/etc/logrotate.d/nodejs
配置文件:
/path/to/your/nodejs/*.log {
daily # 每天轮转
missingok # 文件不存在不报错
rotate 7 # 保留7天
compress # 压缩旧日志
notifempty # 空文件不轮转
create 0640 root adm # 新日志权限
}
6. 高级性能分析工具
--inspect
标志启动应用,用Chrome的Performance面板分析CPU、内存使用:node --inspect app.js
然后在Chrome中打开chrome://inspect
,点击“Open dedicated DevTools for Node”进行调试。