1

log4javascript 打印 log4javascript js 文件的行号。

日志消息.... log4javascript_uncompressed.js:1881

如何打印将实际日志放置在日志消息中的行号?示例: 日志消息.... app.js:15

4

1 回答 1

1

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")

上面的脚本产生以下输出:

[Line#31] 这是一个测试

于 2015-01-26T12:34:00.127 回答