Here's a way to keep your existing console logging statements while adding a file name and line number or other stack trace info onto the output:
(function () {
'use strict';
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !!window.chrome.webstore;
Object.defineProperties(console, ['log', 'info', 'warn', 'error'].reduce(function (props, method) {
var _consoleMethod = console[method].bind(console);
props[method] = {
value: function MyError () {
var stackPos = isOpera || isChrome ? 2 : 1;
var st = (new Error()).stack.split('\n')[1];[stackPos]; // We could utilize the whole stack after the 0th index
arguments[0] += ' \u00a0 (' + st.slice(0, st.lastIndexOf(':')) // Strip out character count
.slice(st.lastIndexOf('/') + 1) + ')'; // Leave only path and line (which also avoids ":" changing Safari console formatting)
return _consoleMethod.apply(null, arguments);
}
};
return props;
}, {}));
}());
Then use it like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="console-log.js"></script>
</head>
<body>
<script>
function a () {
console.log('xyz'); // xyz (console-log.html:10)
}
console.info('abc'); // abc (console-log.html:12)
console.log('%cdef', "color:red;"); // (IN RED:) // def (console-log.html:13)
a();
console.warn('uuu'); // uuu (console-log.html:15)
console.error('yyy'); // yyy (console-log.html:16)
</script>
</body>
</html>
This works in Firefox and, Opera, Safari but notand Chrome (though see @kzahel's solution for Chromenot yet tested on IE).