ubuntu

如何在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
看了该问题的人还看了