lexica98
lexica98

Reputation: 211

Custom console.log function that tells you the line that it was invoked

Here's a simple console.log function that outputs stuff to the console:

function u(x) { console.log(x); } // line 41

But this is not altogether efficient for debugging purposes, as the browser will always output the line that console.log() was invoked on, which is line 41 in this case.

The error or whatever could be on line 741, but it would not matter. I realize that I could simply use console.log all the time instead of creating a shorter custom function, but if I don't have to, well...

How could u(x) display the actual line that it was invoked on?

Cheers!

Upvotes: 1

Views: 79

Answers (3)

Popnoodles
Popnoodles

Reputation: 28409

It's very simple to send the line number to the function. I'm not sure it's so simple to trace without a larger solution.

function u(x, l){
    console.log(x + ' on line ' + l);
}

u('test', new Error().lineNumber)

EDIT: However, I've learned this only works in FF and Opera. There is a cross-browser solution here https://github.com/stacktracejs/stacktrace.js

Upvotes: 1

Ben
Ben

Reputation: 867

In at least chrome you can call console.trace() to log a stack trace to the console.

Edit:

function u(x) {
    console.log(x);
    console.trace();
}

Should give you what you want.

Upvotes: 0

Amir Raminfar
Amir Raminfar

Reputation: 34150

You are asking a difficult question because I have to get in to handling exceptions and what is the correct way to do that. Typically in languages like Java, you pass around exceptions instead of error messages. You could do something like

u(new Error("this is my error"))

in function(e) you could do console.log(e) where that prints the correct stack of the current execution.

Look at How to get JavaScript caller function line number? How to get JavaScript caller source URL? on how to get the actual line number.

Hope this helps.

Upvotes: 1

Related Questions