我正在使用winston制作自记录程序,这允许我在日志记录中添加时间戳和行号。代码可以完成每个功能,但组合后,它们无法按预期工作。
// **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);
}
但是,添加行号配置时,日志记录的时间戳将消失。
例如,在添加行号配置之前。
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
我能解决这个问题吗?
答案 0 :(得分:3)
我让这个工作,这就是我做的。
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问题:I want to display the file Name in the log statement)。我在winston.levels上做了for循环,所以我将拾取所有函数,而不仅仅是信息。
你的原因是你的logger_info_old来自winston,而不是来自logger。所以
var logger_info_old = winston.info;
应该是
var logger_info_old = logger.info;
答案 1 :(得分:3)
我更新了@ jeff-whiting的答案(使用闭包和修复字符串插值)并使其成为单一功能。
通过现有记录器将callsite信息添加到其级别功能
注意logger.log()
未更改,仅更改了logger.{level}()
。
// add callsite info to winston logger instance
function addCallSite(logger) {
// WARNING: traceCaller is slow
// http://stackoverflow.com/a/20431861/665507
// http://stackoverflow.com/a/13411499/665507
/**
* examines the call stack and returns a string indicating
* the file and line number of the n'th previous ancestor call.
* this works in chrome, and should work in nodejs as well.
*
* @param n : int (default: n=1) - the number of calls to trace up the
* stack from the current call. `n=0` gives you your current file/line.
* `n=1` gives the file/line that called you.
*/
function traceCaller(n) {
if( isNaN(n) || n<0) n=1;
n+=1;
var s = (new Error()).stack
, a=s.indexOf('\n',5);
while(n--) {
a=s.indexOf('\n',a+1);
if( a<0 ) { a=s.lastIndexOf('\n',s.length); break;}
}
b=s.indexOf('\n',a+1); if( b<0 ) b=s.length;
a=Math.max(s.lastIndexOf(' ',b), s.lastIndexOf('/',b));
b=s.lastIndexOf(':',b);
s=s.substring(a+1,b);
return s;
}
// assign to `logger.{level}()`
for (var func in logger.levels) {
(function (oldFunc) {
logger[func] = function() {
var args = Array.prototype.slice.call(arguments);
if (typeof args[0] === 'string') {
args[0] = traceCaller(1) + ' ' + args[0];
}
else {
args.unshift(traceCaller(1));
}
oldFunc.apply(logger, args);
};
})(logger[func]);
};
}