log4javascript打印log4javascript js文件的行号。
记录消息.... log4javascript_uncompressed.js:1881
如何在日志消息中打印实际日志的行号? 例: 记录消息.... app.js:15
答案 0 :(得分:0)
AFAIK,log4javascript中的PatternLayout没有实现文件名/行号的说明符。有几个用户提出了功能请求。
以下是您可以自行实施的示例:https://code.google.com/p/aost/source/browse/trunk/tools/firefox-plugin/trump/chrome/content/logger.js?r=858
Tim指出,上面的链接包含了log4js的代码。
编辑:所以,从中获取一个提示,这里是与log4javascript一起使用的代码:
注意:这仅适用于Firefox!
/**
Throw a fake exception to retrieve the stack trace and analyze it
to find the line number from which this function was called
*/
var getLineNumber = function(layout, loggingReference) {
try {(0)()} catch (e) {
/* Split the stack trace */
output = e.stack.replace(/^.*?\n/,'').replace(/(?:\n@:0)?\s+$/m,'').replace(/^\(/gm,'{anon}(').split("\n");
/* The last trace in the array is the filename/line number of the line that logged this */
log_location = output.pop().split(':');
/* Extract the line number from this trace */
line = log_location[log_location.length - 2]
return line;
}
}
logger = log4javascript.getLogger("main");
/* Configure the logger object: add a pop-up appender */
var logAppender = new log4javascript.PopUpAppender();
/* Set a PatternAppender with a custom field */
var popUpLayout = new log4javascript.PatternLayout("[Line#%f] %m");
/* Use the method getLineNumber() as the value for the 0th custom field */
popUpLayout.setCustomField('line', getLineNumber);
logAppender.setLayout(popUpLayout);
logger.addAppender(logAppender);
/* A test log */
logger.info("This is a test")
上面的脚本产生以下输出:
[第31行]这是一个测试