溫馨提示×

Debian Node.js日志中的網絡請求分析

小樊
43
2025-06-13 05:27:08
欄目: 編程語言

在Debian系統上分析Node.js應用程序的網絡請求日志,可以通過以下幾種方法和工具進行:

日志記錄方法

  1. 使用Morgan中間件記錄HTTP請求日志

    • 安裝Morgan:npm install morgan
    • 使用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');
      });
      
  2. 自定義日志格式

    • Morgan允許自定義日志格式,可以包含響應時間:
      app.use(morgan('method url status res[content-length] - response-time ms'));
      
  3. 使用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');
    });
    
  4. 使用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();
    });
    

日志分析工具

  1. ELK Stack(Elasticsearch, Logstash, Kibana)

    • 日志采集:使用Filebeat或Logstash收集日志。
    • 日志存儲:將日志存儲在Elasticsearch中。
    • 日志分析:使用Kibana創建儀表板,可視化請求響應時間等指標。
  2. Wireshark圖形化工具

    • Wireshark是一個強大的網絡協議分析器,可以幫助你更直觀地查看和分析網絡數據包。

通過上述方法,可以有效地記錄和分析Node.js應用中的網絡請求日志,幫助開發者監控和優化應用性能。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女