在Debian系統上分析Node.js應用程序的網絡請求日志,可以通過以下幾種方法和工具進行:
使用Morgan中間件記錄HTTP請求日志:
npm install morgan
const express = require('express');
const morgan = require('morgan');
const app = express();
// 使用morgan中間件,預定義格式為'tiny'
app.use(morgan('tiny'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
自定義日志格式:
app.use(morgan('method url status res[content-length] - response-time ms'));
使用Koa中間件記錄響應時間:
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
let stime = new Date().getTime(); // 記錄當前時間戳
await next(); // 事件控制權中轉
let etime = new Date().getTime(); // 所有中間件執行完成后記錄當前時間
console.log(`請求地址: ${ctx.path} ,響應時間: ${etime - stime} ms`);
});
app.use(async (ctx, next) => {
console.log('中間件 doSomething');
await next();
console.log('中間件執行 over');
});
app.listen(3000, () => {
console.log('server is running at http://localhost:3000');
});
使用Winston記錄日志:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const responseTime = Date.now() - start;
logger.info({ req: req.method, reqUrl: req.url, res: res.statusCode, responseTime: responseTime + ' ms' });
});
next();
});
使用ELK(Elasticsearch, Logstash, Kibana)堆棧進行日志采集和分析:
使用Wireshark圖形化工具分析網絡數據包:
通過上述方法,可以有效地記錄和分析Node.js應用中的網絡請求日志,幫助開發者監控和優化應用性能。