溫馨提示×

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

小樊
36
2025-06-24 20:27:25
欄目: 編程語言

在Ubuntu上自定義Node.js日志格式,你可以使用以下方法:

  1. 使用morgan中間件:

morgan是一個流行的HTTP請求日志中間件,可以幫助你輕松地記錄和自定義日志格式。首先,你需要安裝morgan

npm install morgan

然后,在你的Node.js應用程序中引入并配置morgan

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

const app = express();

// 自定義日志格式
morgan.token('customFormat', function (req, res) {
  return `${req.method} ${req.url} - ${res.statusCode} ${req.responseTime}ms`;
});

app.use(morgan('customFormat'));

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

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

在這個例子中,我們創建了一個名為customFormat的自定義日志格式,其中包括請求方法、URL、狀態碼和響應時間。然后,我們將此自定義格式傳遞給morgan中間件。

  1. 使用winston日志庫:

winston是一個功能強大的日志庫,可以幫助你輕松地記錄和自定義日志格式。首先,你需要安裝winston

npm install winston

然后,在你的Node.js應用程序中引入并配置winston

const express = require('express');
const winston = require('winston');

const app = express();

// 創建一個自定義的winston日志格式
const customFormat = winston.format.combine(
  winston.format.colorize(),
  winston.format.printf(({ timestamp, level, message }) => {
    return `[${timestamp}] ${level}: ${message}`;
  })
);

// 創建一個winston日志記錄器實例
const logger = winston.createLogger({
  level: 'info',
  format: customFormat,
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' }),
  ],
});

app.use((req, res, next) => {
  logger.info(`${req.method} ${req.url}`);
  next();
});

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

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

在這個例子中,我們創建了一個名為customFormat的自定義日志格式,其中包括時間戳、日志級別和消息。然后,我們將此自定義格式傳遞給winston日志記錄器實例。

這兩種方法都可以幫助你在Ubuntu上自定義Node.js日志格式。你可以根據自己的需求選擇合適的方法。

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