Node.js日志中HTTP请求分析技巧
要分析HTTP请求,首先需通过中间件记录结构化日志。常用中间件包括:
app.use(morgan('combined'))使用Apache combined格式);通过日志提取以下核心指标,识别请求中的异常或性能瓶颈:
grep筛选不同状态码(如grep ' 404 ' access.log查404错误,grep ' 500 ' access.log查服务器错误),统计错误率;:response-time token),用awk计算平均值(如awk '{print $NF}' access.log | cut -d'"' -f4 | awk -F':' '{sum += $1} END {print "Average: " sum/NR " ms"}');awk提取URL并排序(如awk '{print $6}' access.log | cut -d'"' -f2 | sort | uniq -c | sort -nr),找出访问量大的接口。Linux命令行工具是日志分析的“轻量级武器”,适合快速处理:
grep 'POST /api/login' access.log查登录接口请求);awk -F'"' '{print $6}' access.log | sort | uniq -c统URL出现次数);sed 's/.*\([0-9]\{3\}\).*/\1/' access.log提取状态码);tail -f error.log监控错误)。对于大规模或分布式系统,需借助专业工具提升分析效率:
%{TIMESTAMP_ISO8601:timestamp} - %{IPORHOST:clientip} %{LOGLEVEL:level} %{PATH:path});将HTTP请求日志与错误日志、系统日志、数据库日志关联,还原用户操作全流程,快速定位根因:
requestId(需在日志中添加唯一标识),关联错误日志中的相同requestId,找到导致错误的请求详情;journalctl -u your-node-service),查看请求期间的系统资源使用情况(CPU、内存),判断是否因资源不足导致请求失败。编写脚本或使用工具实现自动化分析,及时发现问题:
import re; from collections import Counter; with open('access.log') as f: errors = [line for line in f if ' 404 ' in line]; print(f"Daily 404 count: {len(errors)}"));winston-daily-rotate-file或Linux的logrotate工具,避免日志文件过大(如每天生成新日志,保留7天);采用结构化日志(如JSON格式),便于后续用工具解析:
const winston = require('winston');
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [new winston.transports.File({ filename: 'combined.log' })]
});
// 记录HTTP请求日志
logger.info('HTTP Request', { method: 'GET', url: '/', status: 200, responseTime: 50 });
method、url、status等字段,无需复杂正则表达式,提升分析准确性。