您是否有关于如何对节点js winston日志记录方法(如信息)进行猴子修补的想法,请使用shimmer(https://www.npmjs.com/package/shimmer)进行调试?
例如, 这是我的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消息通知。谢谢。
答案 0 :(得分:0)
有两种方法可以实现此目的:
A。 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()
,并在{{1} }。