JavaScript抽象控制台日志记录

9
我希望能够创建一个类似如下的函数。
例如:
function Logger() {
    this.log = function(msg) {
        console.log(msg);
    }
}

我想在函数/模块等中使用它,这些都可以正常工作。 但是我的浏览器默认控制台通常会输出文件名+行号。
现在当我抽象化此功能时,fileNamelineNumber不在我放置实例.log()的位置。因为它将显示调用console.log的位置,而不是函数本身。
所以我的问题是:
如何从我想要使用记录器的位置获取正确的信息? 请给我一些改善此功能的提示。

你使用的日志应用程序是哪个,可以显示行号和文件名? - ar3
默认检查器,适用于Chrome、Safari等。 - Barry
3个回答

16

0

尝试使用类似这样的backtrace函数:

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'));
}

谢谢,您能否更明确一些,它具体是做什么的,何时或如何使用它? - Barry

0
尝试分配函数:
(function () {
    window.log = (console && console.log 
        ? console.log 
        : function () { 
              // Alternative log
          });
})();

稍后在您的代码中调用log('Message')即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接