温馨提示×

Ubuntu Node.js日志中如何设置时间戳

小樊
48
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