ubuntu

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

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

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

启用Node.js日志

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');
});
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进程

sudo npm install pm2 -g
pm2 start app.js --name my-app
pm2 logs my-app

使用 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;
  }
}
sudo systemctl restart nginx

使用 tcpdump 抓包分析

sudo apt-get install tcpdump
sudo tcpdump -i eth0 port 80 -w capture.pcap

使用 Wireshark 分析抓包文件

sudo apt-get install wireshark

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

查找和分析慢请求日志

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
看了该问题的人还看了