溫馨提示×

Node.js在Debian上如何自定義日志格式

小樊
45
2025-05-01 17:37:41
欄目: 編程語言

在Debian上使用Node.js自定義日志格式,通常涉及以下幾個步驟:

  1. 選擇日志庫:選擇一個適合的日志庫,如 winston、morganpino。這些庫提供了靈活的配置選項來自定義日志格式。

  2. 安裝日志庫:使用npm或yarn安裝所選的日志庫。

  3. 配置日志格式:根據所選庫的文檔,配置日志格式。

以下是使用 winstonmorgan 的示例:

使用 Winston

  1. 安裝 Winston

    npm install winston
    
  2. 配置 Winston

    const winston = require('winston');
    
    const logger = winston.createLogger({
      level: 'info',
      format: winston.format.combine(
        winston.format.timestamp({
          format: 'YYYY-MM-DD HH:mm:ss'
        }),
        winston.format.printf(({ timestamp, level, message }) => {
          return `${timestamp} ${level}: ${message}`;
        })
      ),
      transports: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'error.log', level: 'error' }),
        new winston.transports.File({ filename: 'combined.log' })
      ]
    });
    
    logger.info('Hello, world!');
    

使用 Morgan

  1. 安裝 Morgan

    npm install morgan
    
  2. 配置 Morgan

    const express = require('express');
    const morgan = require('morgan');
    
    const app = express();
    
    // 自定義 Morgan 日志格式
    morgan.token('customFormat', (req, res) => {
      return `${req.method} ${req.url} - ${res.statusCode}`;
    });
    
    app.use(morgan('customFormat'));
    
    app.get('/', (req, res) => {
      res.send('Hello, world!');
    });
    
    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
    

總結

  • Winston:提供了更靈活的日志格式化選項,適合復雜的日志需求。
  • Morgan:主要用于HTTP請求日志,配置簡單,適合快速集成。

根據你的具體需求選擇合適的日志庫,并按照其文檔進行配置即可。

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