1

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

Nitul
  • 997
  • 12
  • 35

1 Answers1

1

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

dotbugfix
  • 449
  • 5
  • 6
  • 1
    This code is for log4js rather than log4javascript. They are similar but not the same. – Tim Down Jan 27 '15 at 10:26
  • Took me a while to realize @TimDown is the author of log4javascript! I can imagine you'd be frustrated by the number of times people confuse `log4js` with `log4javascript`! I edited the answer to include an example that works with `log4javascript` (with a note that it will, as you rightly mentioned in your answer, only work on Firefox) – dotbugfix Jan 27 '15 at 14:04