在node.js winston中添加行号配置以进行日志记录时,时间戳消失 [英] timestamps disappear when adding the line number configuration in node.js winston for logging
问题描述
我正在使用Winston制作自记录器,这使我可以在记录中添加时间戳和行号.该代码可以各自完成功能,但是结合使用后,它们将无法按预期工作.
I am using winston to make a self logger, which allow me to add the timestamps and line number in the logging. The code can accomplish the functionality each, but when combined, they don't work as expected.
// **help to add timestamp**
var logger = new (winston.Logger)({
transports : [new (winston.transports.Console)({
json : false,
timestamp : true,
colorize: true
}), new winston.transports.File({
filename : __dirname + '/debug.log',
json : true
})]
,exitOnError : false
});
// **help me to add line number**
var logger_info_old = winston.info;
logger.info = function(msg) {
var fileAndLine = traceCaller(1);
return logger_info_old.call(this, fileAndLine + ":" + msg);
}
但是,添加行号配置后,日志记录的时间戳将消失.
However, when line number configuration is added, timestamp for the logging will disappear.
例如,在添加行号配置之前.
For example, before adding the line number configuration.
logger.info("abc");
2013-11-24T09:49:15.914Z - info:339:abc
添加行号配置时
logger.info("abc");
info: (H:\Dropbox\node\fablab\utils\logging.js:85:abc
我想要的最佳结果就像
logger.info("abc");
2013-11-24T09:49:15.914Z - info: (H:\Dropbox\node\fablab\app.js:339:abc
我可以解决这个问题吗?
Can I fix this?
推荐答案
我使它起作用,这就是我的方法.
I got this to work and this is how I did it.
var transports = [
new(winston.transports.Console)({
colorize: true,
prettyPrint: true,
timestamp : true,
level: 'debug',
})
];
var log = new(winston.Logger)({
"transports": transports
});
for (var func in winston.levels) {
var oldFunc = log[func];
log[func] = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(traceCaller(1));
oldFunc.apply(log, args);
}
}
这样我就得到了时间戳和文件.(请注意traceCaller(1)来自以下stackoverflow问题:
With that I got both the timestamp and the file. (note traceCaller(1) is from this stackoverflow question: I want to display the file Name in the log statement). I did the for loop over the winston.levels so I would pickup all the functions not just info.
您不工作的原因是您的logger_info_old来自Winston,而不是来自logger.所以
The reason yours didn't work was your logger_info_old was from winston and not from logger. So
var logger_info_old = winston.info;
应该是
var logger_info_old = logger.info;
这篇关于在node.js winston中添加行号配置以进行日志记录时,时间戳消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!