在Ubuntu系统中追踪JS(Node.js)请求流程的第一步,是确保应用具备完善的日志记录能力。常用工具包括内置console
模块、Winston(结构化日志)、Morgan(HTTP请求专用)、Bunyan(JSON格式日志)等。
console.log
记录请求的基本信息(如时间、方法、URL)。例如:app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.File({ filename: 'error.log', level: 'error' })
]
});
app.use((req, res, next) => {
logger.info({ method: req.method, url: req.url, headers: req.headers });
next();
});
const morgan = require('morgan');
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
以上配置完成后,应用会将请求流程信息输出到终端或日志文件中。
Ubuntu系统提供了多种工具查看JS应用的日志,覆盖实时监控、历史检索等场景:
pm2
或systemctl
启动),可使用journalctl
查看服务日志。例如:# 查看所有系统日志
journalctl
# 实时查看特定JS服务(如名为"my-node-app"的服务)的日志
journalctl -u my-node-app -f
combined.log
),可使用tail -f
实时监控新日志。例如:tail -f /path/to/your/app/combined.log
pm2 logs
查看应用的实时日志(包括请求流程信息)。例如:pm2 logs my-app # 查看名为"my-app"的进程日志
pm2 logs all # 查看所有PM2管理的进程日志
这些工具能帮助你快速获取JS应用的日志输出,追踪请求的实时流程。
若需追踪前端JS发起的请求(如Ajax、Fetch),可使用浏览器开发人员工具:
F12
或右键选择“检查”,进入“开发者工具”。console.log
输出,可在“控制台”中查看,辅助排查请求流程中的问题。对于生产环境,建议使用集中化日志管理工具,实现日志的统一收集、存储、搜索和可视化:
elasticsearch
传输插件将日志发送到Elasticsearch,再通过Kibana创建仪表盘追踪请求流程。通过以上方法,你可以在Ubuntu系统中高效追踪JS应用的请求流程,快速定位问题根源。