溫馨提示×

Ubuntu Node.js日志中如何設置時間戳

小樊
41
2025-09-16 04:52:11
欄目: 編程語言

在Ubuntu系統中,為Node.js應用程序設置日志時間戳可以通過多種方式實現。以下是幾種常見的方法:

方法一:使用morgan中間件

morgan是一個流行的HTTP請求日志中間件,可以為Node.js應用程序添加時間戳。

  1. 安裝morgan

    npm install morgan
    
  2. 在你的Node.js應用程序中使用morgan

    const express = require('express');
    const morgan = require('morgan');
    const app = express();
    
    // 使用morgan中間件,并設置格式為自定義格式,包含時間戳
    app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
    
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
    

方法二:使用winston日志庫

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(), // 添加時間戳
        winston.format.json() // 可選:將日志格式化為JSON
      ),
      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!');
    

方法三:手動添加時間戳

如果你不想使用第三方庫,也可以手動為日志添加時間戳。

const fs = require('fs');
const http = require('http');

const server = http.createServer((req, res) => {
  const timestamp = new Date().toISOString();
  const logEntry = `${timestamp} - ${req.method} ${req.url}\n`;

  fs.appendFile('access.log', logEntry, (err) => {
    if (err) throw err;
  });

  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World!\n');
});

server.listen(3000, () => {
  console.log('Server is running on port 3000');
});

方法四:使用morgan和自定義格式

如果你使用morgan并且想要自定義日志格式,可以這樣做:

const express = require('express');
const morgan = require('morgan');
const app = express();

// 自定義morgan格式,包含時間戳
morgan.token('timestamp', () => new Date().toISOString());
app.use(morgan(':timestamp :method :url :status :res[content-length] - :response-time ms'));

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

通過這些方法,你可以在Ubuntu系統中的Node.js應用程序中輕松地添加時間戳到日志中。選擇適合你項目需求的方法即可。

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