Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

console.log line number in debugger

I'm looking for a simple way to make a log function.

I'm calling a function logSuc("return from Prom"), the function is on line 30.

So the code will always point to the line 30 of that function. In the console:

console

So say have this code:

const logSuc = (msg) => {
   console.log(`%c ${msg}`, 'background: green; color: white; display: block;'); 
};

An alternative could be:

const log = console.log;
function red(msg) {
  return `%c ${msg}`, 'background: red; color: white; display: block;';
}
log(red('its red');

But now i have two functions and I want to keep it short and simple

So the problem is my logSuc("") always points to line 30.

But I want it to be point to the line where I call logSuc("that worked").

like image 803
Johan Hoeksma Avatar asked Apr 13 '18 10:04

Johan Hoeksma


People also ask

How do you add a line in console log?

To create a multi line strings when printing to the JavaScript console, you need to add the new line character represented by the \n symbol. Alternatively, you can also add a new line break using Enter when you use the template literals syntax.

What does console log () do?

The console. log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.

How do I use console log code?

console. log() is used as a debugging tool to help you understand what your code is doing. By displaying a message containing either descriptive text that tells you what is happening or the value of particular variables, you can follow along as your code executes. The user of your app will not see the console.


2 Answers

I suggest you replace console.log by console.trace. That way you see where the call comes from, thus solving your problem.

like image 78
Eric J. Francois Avatar answered Oct 27 '22 22:10

Eric J. Francois


The function you get from using Function.prototype.bind on console.log will point to the line number where it’s called. It’s a bit limited, but if you only ever want to pass it one string argument, it’ll work:

const logSuc = console.log.bind(console, '%c %s',
    'background: green; color: white');

Tested in both Firefox and Chrome.

For more complex behaviour, you can manually blackbox the script containing the logging function, as described in this answer for Chrome and by activating the “blackbox” button on a script in the debugger in Firefox (beside {} Pretty print source, an eye icon).

like image 35
Ry- Avatar answered Oct 27 '22 21:10

Ry-