Custom console log function, a console.log wrapper

John picture John · Dec 11, 2013 · Viewed 16.3k times · Source
function log( msgOrObj ){
    if(dev_mode){
        console.log({
            'message': msgOrObj,
            'caller': arguments.callee.caller.toString()
        });
    }
}

So, I have attempted to write a simple custom console log function (as above). However I am struggling to find which file and line the caller came from. The most I can see is the function that called it.

Has anyone done anything similar? Or is this even possible?

example used in somescript.js from line 70:

log('some very important message!')

Answer

Joe picture Joe · Dec 11, 2013

Yes but it's very hacky and not cross browser-safe. You can use this as a starting point. It borrows from this answer.

window.trace = function stackTrace() {
    var err = new Error();
    return err.stack;
}

window.my_log = function (x) {
    var line = trace();
    var lines = line.split("\n");
    console.log(x + " " + lines[2].substring(lines[2].indexOf("("), lines[2].lastIndexOf(")") + 1))
}


window.my_log("What light through yonder window breaks?")

Produces:

What light through yonder window breaks? (<anonymous>:2:42)