Nitul
Nitul

Reputation: 1035

log4javascript - Line no in logs messages

log4javascript prints line no of log4javascript js file.

Log message.... log4javascript_uncompressed.js:1881

How to print the line no from which actual log is placed in log messages? Example: Log message.... app.js:15

Upvotes: 1

Views: 913

Answers (1)

dotbugfix
dotbugfix

Reputation: 459

AFAIK, the PatternLayout in log4javascript doesn't implement a specifier for the filename/line number. There have been feature requests for this from several users.

Here is a sample of how you could implement it by yourself: https://code.google.com/p/aost/source/browse/trunk/tools/firefox-plugin/trump/chrome/content/logger.js?r=858

As Tim pointed out, the above link has code for log4js.

EDIT: So, taking a cue from it, here is the code that would work with log4javascript:

Note: This will work ONLY for 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")

The above script produces the following output:

[Line#31] This is a test

Upvotes: 1

Related Questions