Reputation: 3746
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:
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").
Upvotes: 10
Views: 6712
Reputation: 682
I suggest you replace console.log
by console.trace
. That way you see where the call comes from, thus solving your problem.
Upvotes: 4
Reputation: 224942
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).
Upvotes: 2