linux

Node.js日志格式怎么自定义

小樊
39
2025-09-11 13:19:27
栏目: 编程语言

在 Node.js 中,可以使用第三方库如 winstonmorgan 来自定义日志格式。下面是使用这两个库的示例:

  1. 使用 winston 库自定义日志格式:

首先,安装 winston

npm install winston

然后,创建一个 logger.js 文件,并添加以下代码:

const { createLogger, format, transports } = require('winston');

const myFormat = format.combine(
  format.timestamp(),
  format.printf(({ timestamp, level, message }) => {
    return `[${timestamp}] ${level.toUpperCase()}: ${message}`;
  })
);

const logger = createLogger({
  level: 'info',
  format: myFormat,
  transports: [
    new transports.Console(),
    new transports.File({ filename: 'logs/app.log' })
  ]
});

module.exports = logger;

在这个例子中,我们定义了一个名为 myFormat 的自定义格式,它包含时间戳、日志级别和消息。然后,我们将这个格式传递给 createLogger 函数。

现在,你可以在你的应用程序中使用这个自定义日志记录器:

const logger = require('./logger');

logger.info('Hello, world!');
  1. 使用 morgan 库自定义日志格式:

首先,安装 morgan

npm install morgan

然后,在你的应用程序中使用 morgan

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

const app = express();

const myFormat = ':method :url :status :res[content-length] - :response-time ms - :message';

app.use(morgan(myFormat));

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

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

在这个例子中,我们定义了一个名为 myFormat 的自定义格式,它包含请求方法、URL、状态码、响应内容长度、响应时间和消息。然后,我们将这个格式传递给 morgan 中间件。

现在,当你访问应用程序时,日志将按照自定义格式显示。

这两个示例展示了如何在 Node.js 中使用第三方库自定义日志格式。你可以根据自己的需求调整格式和选项。

0
看了该问题的人还看了