Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom console log function, a console.log wrapper

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!')
like image 948
John Avatar asked Dec 11 '13 16:12

John


People also ask

How do you wrap a console log?

Type it and press Ctrl+Alt+W + W . Another way to console. log your variables is to simply place your mouse cursor on them and then wrap them on the line below with Ctrl+Alt+W + Down or the line above with Ctrl+Alt+W + Up .

How do you write a function in console log?

Syntax: console. log(A); Parameters: It accepts a parameter which can be an array, an object or any message.

What is the use of console log () method in node JS?

log() function from console class of Node. js is used to display the messages on the console. It prints to stdout with newline. Parameter: This function contains multiple parameters which are to be printed.

How do you assign a console log to a variable?

If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution. Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.


1 Answers

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) 
like image 92
Joe Avatar answered Oct 05 '22 03:10

Joe