NodeJS - 如何跨项目共享记录器对象?

NodeJS - How is logger object shared across project?

我使用 winston 包在 utils/logger.js 中创建了一个 logger 对象。我的项目的入口点是 index.js,我有 const logger = require('./utils/logger')。我如何 'cascade' 这个记录器对象跨 所有 个项目文件 (~20)?我项目中的每个文件都应该做一个 const logger = require('../utils/logger) 吗?如果是这样,当我做 node index.js 时,它们不都是单独的 logger 对象吗?

我正在为 utils.logger.js 使用以下内容(来自 here)。

var appRoot = require('app-root-path');
var winston = require('winston');

// define the custom settings for each transport (file, console)
var options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
var logger = new winston.Logger({
  transports: [
    new winston.transports.File(options.file),
    new winston.transports.Console(options.console)
  ],
  exitOnError: false, // do not exit on handled exceptions
});

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write: function(message, encoding) {
    // use the 'info' log level so the output will be picked up by both transports (file and console)
    logger.info(message);
  },
};

module.exports = logger;

在我看来,您可以在同一个文件中创建一个用于记录的函数,然后将这些函数导出到您的文件中,这样您就可以在整个项目中使用同一个对象。

utils/logger.js



function InfoLogger(message){
logger.info(message);
}

module.exports = {InfoLogger}

更新:here 的回答中,我了解到 nodejs 总是使用 'require once' 方法。

After you call require the first time, require uses a cache and will always return the same object.

我也在测试项目中尝试了这个,我在文件的开头使用了 console.log 并从文件中导出了一个函数。然后在我的项目中多次导入该函数,而 console.log 仅 运行 一次。

所以您的 var logger = 只会 运行 一次并且您共享同一个对象