A proper wrapper for console.log with correct line number?
I found a simple solution to combine the accepted answer (binding to console.log/error/etc) with some outside logic to filter what is actually logged.
// or window.log = {...}
var log = {
ASSERT: 1, ERROR: 2, WARN: 3, INFO: 4, DEBUG: 5, VERBOSE: 6,
set level(level) {
if (level >= this.ASSERT) this.a = console.assert.bind(window.console);
else this.a = function() {};
if (level >= this.ERROR) this.e = console.error.bind(window.console);
else this.e = function() {};
if (level >= this.WARN) this.w = console.warn.bind(window.console);
else this.w = function() {};
if (level >= this.INFO) this.i = console.info.bind(window.console);
else this.i = function() {};
if (level >= this.DEBUG) this.d = console.debug.bind(window.console);
else this.d = function() {};
if (level >= this.VERBOSE) this.v = console.log.bind(window.console);
else this.v = function() {};
this.loggingLevel = level;
},
get level() { return this.loggingLevel; }
};
log.level = log.DEBUG;
Usage:
log.e('Error doing the thing!', e); // console.error
log.w('Bonus feature failed to load.'); // console.warn
log.i('Signed in.'); // console.info
log.d('Is this working as expected?'); // console.debug
log.v('Old debug messages, output dominating messages'); // console.log; ignored because `log.level` is set to `DEBUG`
log.a(someVar == 2) // console.assert
- Note that
console.assert
uses conditional logging. - Make sure your browser's dev tools shows all message levels!
Wrapping a wrapper of console log with correct file/line number?
You can set default arguments (the string "special: "
) using bind
. So this should work:
specialLog = Function.prototype.bind.call(console.log, console, "Special: ");
// ^^^^^^^^^^^^^^
Explanation:
When specialLog
get called, the first argument passed to console.log
will always be "Special: "
, so if you call it like:
specialLog("Hello, world!");
it will be as if you call console.log
like:
console.log("Special: ", "Hello, world!");
which prints the string: "Special: Hello, world!"
, your desired result.
user7552 (op) edit:
for my case, it would be:
specialLog = Function.prototype.bind.call(this.log, console, "Special:");
using this.log
(reference inside the debugger class), instead of console.log
.
Wrapping console.log with additional function and correct line numbers
Just for anyone who comes across this i wrote a babel plugin to solve this issue:
https://github.com/peteringram0/babel-plugin-console-source
console.log line number in debugger
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).
Get console wrapper to log message on correct line
To be precise on what I did to get the error number including the regex needed to grab it.
var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index+2, caller_line.length);
var number = clean.match(/(?!:)\d*(?=\:)/g);
console.log(number[0]);
how to console.log the number of the line in the code
You can use (new Error()).stack
to get the stack trace at the current line. it would require some additional parsing to get the line number however.
e.g., console.log((new Error()).stack.split(':')[1])
will get it assuming it is at the root of the file, but once you start adding it to functions you'd need something a little more sophisticated.
console.log(
"❌ the error is on the line N." +
new Error().stack.split(":")[3]
);
Related Topics
How to Download File from Server
How to Search JSON Tree with Jquery
Dc.Js - How to Create a Row Chart from Multiple Columns
(Deep) Copying an Array Using Jquery
Find Out How Long an Ajax Request Took to Complete
Returning a Value from Callback Function in Node.Js
Puppeteer Page.Evaluate Queryselectorall Return Empty Objects
Jquery Difference Between Change and Click Event of Checkbox
Firefox 'Cross-Origin Request Blocked' Despite Headers
Jquery .On() Method with Multiple Event Handlers to One Selector
Automatic Semicolon Insertion & Return Statements
Split String Only on First Instance of Specified Character
How to Calculate the Latlng of a Point a Certain Distance Away from Another
Retrieving Binary File Content Using JavaScript, Base64 Encode It and Reverse-Decode It Using Python
Why Does an Onclick Property Set with Setattribute Fail to Work in Ie
Fulfill (Don't Resolve) Promise with Another Promise
Jquery Function to Get All Unique Elements from an Array
How to Implement Cross Domain Url Access from an Iframe Using JavaScript