7

Is it possible using some javascript trickery to tell console.log which line number it should output?

Suppose, we the following simple example:

function Logger () {
    this.debug = function(msg) {
        // do some stuff with msg
        console.log(msg);
    };
}

var log = new Logger();
log.debug("Hello");

If you open the page, Chrome shows up this:

enter image description here

This indicates that the message was logged at main.js:4 but what I really want is that it shows main.js:9. Because line 9 is where the logger was called. For this simple case it doesn't make much difference, but when the Logger is in a separate file, it always shows logger.js instead of the class which called the logger.

The Logger class should do some additional stuff with the logged message (e.g. sending it to the server), thus I can't just use this.debug = console.log.

EDIT:

There are already some similar questions, but all of them just add an additional line to the output, which isn't clickable to jump to the corresponding line:

Community
  • 1
  • 1
Stefan Profanter
  • 6,458
  • 6
  • 41
  • 73

1 Answers1

4

The first thing that comes to my mind is creating a new Error object to get the stack trace and then find the line that called your method, like this:

function Logger () {
    this.debug = function(msg) {
        // do some stuff with msg

        //TODO: document this line
        var callerLine = new Error().stack.split('\n')[2];
        console.log(msg, callerLine);
    };
}

var log = new Logger();
log.debug("Hello");

Basically I'm splitting the error's stack in each newline and ignoring the first and second lines (The error message and your own method in the stack, respectively).

William Barbosa
  • 4,936
  • 2
  • 19
  • 37
  • This is a solution which is not yet perfect. The output is now: `Hello at http://localhost/main.js:12:5 main.js:7` It would be nicer to have just the relative path. – Stefan Profanter Aug 27 '15 at 15:09
  • Unforunately the Error.prototype.stack property is non standard conform, so this isn't a valid solution. See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Error/stack – Stefan Profanter Aug 28 '15 at 12:46
  • This code is not even meant to work in production because your JS should be minified, fitting everything in as few lines as possible. This is not meant to be a cross-browser thing, just a way to simplify logging, so I don't see how not being a standard makes this a "invalid solution" – William Barbosa Aug 28 '15 at 12:50
  • Well the problem is that I'm using Typescript which complains at this line that `TS2339: Property 'stack' does not exist on type 'Error'.` – Stefan Profanter Aug 28 '15 at 12:52