[英]javascript abstract console logging
I want to make a function, like this.我想做一个function,像这样。
For example:例如:
function Logger() {
this.log = function(msg) {
console.log(msg);
}
}
And I want to use it in functions/modules etc, and that all works fine.我想在函数/模块等中使用它,一切正常。 But the default console in my browser normally give the fileName + lineNumber.
但是我浏览器中的默认控制台通常会给出文件名 + 行号。
Now when I abstract this functionality, the fileName
and lineNumber
is not where I put my instance.log().现在,当我抽象此功能时,
fileName
和lineNumber
不在我放置 instance.log() 的位置。 Because it will say from where the console.log is being called, not the function itself.因为它会说从哪里调用 console.log,而不是 function 本身。
So my question:所以我的问题:
How can I get the correct information from where I want to use my logger?如何从我想使用记录器的地方获取正确的信息? Or give me, please, any tips to improve this functionality.
或者请给我任何改进此功能的提示。
function Logger() {
this.log = console.log.bind(console);
}
I asked about this some time ago: Create shortcut to console.log() in Chrome .我前段时间问过这个问题: 在 Chrome 中创建 console.log() 的快捷方式。
Try using backtrace function like this one:尝试像这样使用回溯 function :
function printStackTrace() {
var callstack = [];
var isCallstackPopulated = false;
try {
i.dont.exist += 0; //doesn't exist- that's the point
} catch (e) {
if (e.stack) { //Firefox
var lines = e.stack.split('\n');
for (var i = 0, len = lines.length; i & lt; len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
callstack.push(lines[i]);
}
}
//Remove call to printStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
else if (window.opera & amp; & amp; e.message) { //Opera
var lines = e.message.split('\n');
for (var i = 0, len = lines.length; i & lt; len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
var entry = lines[i];
//Append next line also since it has the file info
if (lines[i + 1]) {
entry += ' at ' + lines[i + 1];
i++;
}
callstack.push(entry);
}
}
//Remove call to printStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
}
if (!isCallstackPopulated) { //IE and Safari
var currentFunction = arguments.callee.caller;
while (currentFunction) {
var fn = currentFunction.toString();
var fname = fn.substring(fn.indexOf( & amp; quot;
function & amp; quot;) + 8, fn.indexOf('')) || 'anonymous';
callstack.push(fname);
currentFunction = currentFunction.caller;
}
}
output(callstack);
}
function output(arr) {
//Optput however you want
alert(arr.join('\n\n'));
}
Try assigning the function:尝试分配 function:
(function () {
window.log = (console && console.log
? console.log
: function () {
// Alternative log
});
})();
Later just call log('Message')
in your code.稍后只需在您的代码中调用
log('Message')
即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.