要有效分析网络请求,需先确保Node.js应用生成详细、结构化的日志。常用工具包括:
console.log:简单记录请求基本信息(如URL、状态码),但缺乏结构化,适合快速调试。morgan中间件(Express推荐):专为HTTP请求设计,可生成包含方法、URL、状态码、响应时间的结构化日志(如Apache combined格式)。示例配置:const morgan = require('morgan');
app.use(morgan(':method :url :status :response-time ms - :res[content-length]'));
winston日志库:支持多传输(文件、控制台、数据库)、日志分级(info/warn/error),适合生产环境。可配置JSON格式日志,便于后续解析。示例配置:const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [new winston.transports.File({ filename: 'access.log' })]
});
app.use((req, res, next) => {
logger.info({ method: req.method, url: req.url, status: res.statusCode, responseTime: res.responseTime });
next();
});
winston-daily-rotate-file等库避免日志文件过大,例如每天生成一个新日志文件并压缩旧文件。app.log、access.log),可通过重定向实现:node app.js > app.log 2>&1 # 合并stdout和stderr到app.log
pm2管理Node.js进程,可通过pm2 logs my-app查看实时日志;或通过journalctl查看系统日志(适用于systemd管理的服务):sudo journalctl -u your-node-service.service -f # 实时查看服务日志
通过关键词过滤日志中的错误信息,例如:
grep ' 404 ' access.log # 统计404请求数
grep ' 500 ' access.log # 查看500错误详情
grep -i 'error' app.log # 查找所有错误日志(不区分大小写)
pm2 logs结合--filter选项:pm2 logs my-app --filter "error" # 只显示包含“error”的日志
计算平均响应时间、识别慢请求(如超过1秒的请求):
awk '{print $NF}' access.log | cut -d'"' -f4 | awk -F':' '{sum += $1} END {print "Average response time: " sum/NR " ms"}'
awk '$NF > 1000 {print $0}' access.log # NF表示最后一列(响应时间)
wc -l access.log # 统计日志行数(即总请求数)
grep '"GET /"' access.log | wc -l # 统计GET /请求的数量
awk -F'"' '{print $6}' access.log | sort | uniq -c | sort -nr # 提取UA并排序
使用ELK Stack(Elasticsearch+Logstash+Kibana)实现:
input { file { path => "/path/to/access.log" start_position => "beginning" codec => "json" } }
output { elasticsearch { hosts => ["localhost:9200"] index => "nodejs-access-%{+YYYY.MM.dd}" } }
若日志中出现网络相关错误(如ECONNREFUSED、ETIMEDOUT),需进一步排查:
ping测试目标服务器可达性,traceroute追踪路由路径:ping example.com
traceroute example.com
nslookup或dig验证域名解析是否正确:nslookup example.com
dig example.com
tcpdump捕获网络流量,Wireshark可视化分析TCP连接状态、丢包或延迟问题:sudo tcpdump -i eth0 port 80 -w capture.pcap # 捕获80端口的流量
http模块或axios):const http = require('http');
const options = { hostname: 'example.com', port: 80, path: '/', method: 'GET', timeout: 5000 }; // 5秒超时
通过以上步骤,可系统分析Ubuntu Node.js日志中的网络请求,快速定位问题、优化性能并了解用户行为。