温馨提示×

Ubuntu Node.js日志中的请求跟踪技术

小樊
63
2025-07-21 04:06:55
栏目: 编程语言

在Ubuntu系统中,通过日志追踪Node.js应用程序的请求流程可以帮助你了解应用程序的运行状况、性能瓶颈以及潜在的问题。以下是一些步骤和工具,可以帮助你实现这一目标:

启用Node.js日志

  • 使用内置的 console.log
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  console.log('Request received at', new Date());
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
  • 使用更高级的日志库如 winstonmorgan
const express = require('express');
const winston = require('winston');
const app = express();

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' }),
  ],
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({ format: winston.format.simple() }));
}

app.get('/', (req, res) => {
  logger.info('Request received at', new Date());
  res.send('Hello World!');
});

app.listen(3000, () => {
  logger.info('Server is running on port 3000');
});

使用 pm2 管理Node.js进程

  • 安装 pm2
sudo npm install pm2 -g
  • 启动应用程序
pm2 start app.js --name my-app
  • 查看日志
pm2 logs my-app

使用 nginx 作为反向代理

  • 配置 nginx 日志

编辑 /etc/nginx/sites-available/default 文件,添加以下内容:

server {
  listen 80;
  server_name yourdomain.com;

  location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
  }
}
  • 重启 nginx
sudo systemctl restart nginx

使用 tcpdump 抓包分析

  • 安装 tcpdump
sudo apt-get install tcpdump
  • 抓包
sudo tcpdump -i eth0 port 80 -w capture.pcap

使用 Wireshark 分析抓包文件

  • 安装 Wireshark
sudo apt-get install wireshark
  • 打开抓包文件

启动 Wireshark 并打开 capture.pcap 文件进行分析。

查找和分析慢请求日志

  • 使用 console.time()console.timeEnd() 记录请求时间
console.time('requestTime');
// 执行请求逻辑
console.timeEnd('requestTime');
  • 使用日志库记录详细日志
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' }),
  ],
});

app.use((req, res, next) => {
  logger.info({ method: req.method, url: req.url, responseTime: Date.now() - req.start, status: res.statusCode });
  next();
});
  • 分析日志文件

使用命令行工具如 tailgrep 等来分析日志文件,找出耗时较长的请求。

通过上述方法,你可以有效地追踪和分析Ubuntu系统中Node.js应用程序的请求流程。

0