log4javascript打印log4javascript js文件的行号。

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

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

最佳答案

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行]这是一个测试

08-03 15:43