0

您是否知道如何使用 shimmer(https://www.npmjs.com/package/shimmer)对节点 js winston 日志记录方法(如信息、调试)进行猴子修补?

例如,这是我的 winston 3.x 设置:

let winston = require('winston')
   winstonInit = winston.createLogger({
      format: winston.format.json(),
      transports: [
        new winston.transports.Console({ level: 'info' }),
        new winston.transports.File({
          name: 'winston-logging',
          level: 'info',
          filename: './log/winston.log',
          handleExceptions: true
        })
      ],
      exceptionHandlers: [
        new winston.transports.File({ filename: './log/exceptions.log', handleExceptions: true})
      ]
    });
    winston.add(winstonInit);

因此,在我的应用程序中,我可以调用它 winston.info('send this message to Slack') // output: send this message to Slack。除了显示消息,我们还执行其他功能。

我只想修补这个 winston.info() ,比如添加一些额外的功能,例如在执行 winston.info 时发送 Slack 消息通知。谢谢。

4

1 回答 1

0

有两种方法可以实现这一点:

一、shimmer方式:

var shimmer = require('shimmer');

// Assuming that an instance of winston is accesible.
shimmer.wrap(winston, 'info-interceptor', (winstonCall) => {
    return function(arguments) {
        // arguments are the log messages sent to the winston method for logging.
        console.log(arguments)
        
        // check if executed winston function is winston.info or not.
        if(winstonCall.name === 'info'){
           // add logic to send arguments to a slack message
        }
        
        // it is important to return the original call.
        retirm winstonCall;
    }
});

注意:不建议使用该function.name方法,因此我建议不要使用微光方式。

B、non-shimmer方式

每当 info 方法以下列方式执行时,您可以更新您的 winston 配置以执行附加功能:

let winston = require('winston')
   winstonInit = winston.createLogger({
      format: winston.format.json(),
      transports: [
        new winston.transports.Console({ level: 'info' }),
        new winston.transports.File({
          name: 'winston-logging',
          level: 'info',
          filename: './log/winston.log',
          handleExceptions: true
        }),
        new HttpStreamTransport({
            url: 'https://yourdomain.com/log'
        })
      ],
      exceptionHandlers: [
        new winston.transports.File({ filename: './log/exceptions.log', handleExceptions: true})
      ]
    });
    
    // winston.add(winstonInit);

    const logger = {
       _sendMessageToSlack: (msg) => {
           // logic for sending message to slack
        
           return message;
       },
       info: (msg) => winstonInit.info(logger._sendMessageToSlack(msg)),
       warn: (msg) => winstonInit.warn(msg),
       error: (msg) => winstonInit.error(msg),
   };

module.exports = logger;

这将允许您在各种文件中导入logger实例并将其用作logger.info(), logger.warn()logger.error()并在调用时执行附加功能logger.info

于 2020-07-08T14:17:06.613 回答