在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應用程序的請求流程。