提问者:小点点

Monkey修补节点js winston logging


您知道如何通过使用shimmer(https://www.npmjs.com/package/shimmer)对node js winston日志记录方法(如info,debug)进行修补吗?

例如,这是我的Winston3.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消息通知。 谢了。


共1个答案

匿名用户

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

A.微光方式:

var shimmer = require('shimmer');

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

注意:使用function.name方法是不可取的,因此我建议不要使用shimmer方法。

B.非微光方式

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

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时执行additiona功能。