在Ubuntu系统中,通过日志追踪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');
});
winston
或 morgan
: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();
});
使用命令行工具如 tail
、grep
等来分析日志文件,找出耗时较长的请求。
通过上述方法,你可以有效地追踪和分析Ubuntu系统中Node.js应用程序的请求流程。