在Feathersjs中使用Winston显示相关ID

问题描述 投票:0回答:1

我想使用winston登录FeathersJS。但是,我想用“相关ID”记录。我想找到我应该如何创建记录器,我想只记录消息,而不是提供相关ID。这是一个例子。

log.info('Here is a log');

// output [Info] [correlation-id] : Here is a log

我想知道,如何让我的记录器注入不同的每个请求的相关ID的最佳方法?

node.js feathersjs winston feathers-service
1个回答
1
投票

我有一个问题的解决方案。但我仍然不确定这会有效。我使用的库如

  • cls-hooked(用于作用域请求)
  • uuid(用于生成id)

这是我第一次生成FeathersJS项目后的更改。

src/logger.js中,我使用getNamespace并从命名空间获取变量。这是我的例子:

const { createLogger, format, transports } = require('winston');
const getNamespace = require('cls-hooked').getNamespace;

const myFormat = format.printf(({level, message, timestamp}) => {
  const loggerNamespace = getNamespace('logger');
  return `[${timestamp}] [${level}] [${loggerNamespace.get('correlationId')}]: ${message}`;
});

// Configure the Winston logger. For the complete documentation see https://github.com/winstonjs/winston
const logger = createLogger({
  // To see more detailed errors, change this to 'debug'
  level: 'info',
  format: format.combine(
    format.timestamp(),
    format.splat(),
    myFormat
  ),
  transports: [
    new transports.Console()
  ],
});

module.exports = logger;

在此之后,我完成了设置我的记录器以获取correlationId,现在每个我的请求都要进行相关,我使用中间件来实现这一点。我将添加新的中间件来控制src/middleware/correlation.js中的correlationId。这是我的例子:

const uuidv4 = require('uuid/v4');

function correlation(namespace) {
  return (req, res, next) => {
    const correlationId = uuidv4();
    req.feathers.correlationId = correlationId;
    namespace.run(() => {
      namespace.set('correlationId', correlationId);
      next();
    });
  }
}

module.exports = correlation;

在我创建自己的中间件之后,我会将其注册到src/middleware/index.js的全局中间件中。这是我的变化,

const createNameSpace = require('cls-hooked').createNamespace;
const correlation = require('./correlation');
const logNameSpace = createNameSpace('logger');

// eslint-disable-next-line no-unused-vars
module.exports = function (app) {
  // Add your custom middleware here. Remember that
  // in Express, the order matters.
  app.use(correlation(logNameSpace));
};

在此更改之前,您已设置logger以获取correlationId。例如,我创建了一个钩子,并在那里添加日志。我把它放在src/hooks/logsHooks这里我的例子:

// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
const logger = require('../logger');
// eslint-disable-next-line no-unused-vars
module.exports = function (options = {}) {
  return async context => {
    logger.info('Test my correlation Id');
    let i = 0;
    function recursive() {
      setTimeout(() => {
        logger.debug(`My Itteration ${i}, let it request finish than run this background`);
        i++;
        if (i < 50) {
          recursive();
        }
      }, 5000);
    }
    recursive();
    return context;
  };
};

当我设置它时,我认为这已经符合我的要求。但是我仍然需要用另一个案例来测试这个。我只是用一些简单的案例进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.