JavaScript:如何将消息打印到错误控制台?

时间:2008-10-02 20:23:55

标签: javascript debugging

如何将消息打印到错误控制台,最好包含变量?

例如:

print('x=%d', x);

18 个答案:

答案 0 :(得分:461)

安装Firebug,然后您可以使用console.log(...)console.debug(...)等。(有关详情,请参阅the documentation)。

答案 1 :(得分:308)

console.error(message); //gives you the red errormessage
console.log(message); //gives the default message
console.warn(message); //gives the warn message with the exclamation mark in front of it
console.info(message); //gives an info message with an 'i' in front of the message

您还可以将CSS添加到日志消息中:

console.log('%c My message here', "background: blue; color: black; padding-left:10px;");

答案 2 :(得分:84)

将异常记录到JavaScript控制台中。如果您想要Firebug禁用,可以使用它。

function log(msg) {
    setTimeout(function() {
        throw new Error(msg);
    }, 0);
}

用法:

log('Hello World');
log('another message');

答案 3 :(得分:55)

Debugging JavaScript: Throw Away Your Alerts! 中列出了一种有效的跨浏览器工作方式。

答案 4 :(得分:15)

如果您使用 Safari ,则可以写

console.log("your message here");

它出现在浏览器的控制台上。

答案 5 :(得分:14)

以下是如何将消息打印到浏览器的错误控制台而不是调试器控制台的文字问题的解决方案。 (可能有充分的理由绕过调试器。)

正如我在评论中提到的,在错误控制台中抛出错误以获取消息的建议时,一个问题是这会中断执行的线程。如果您不想中断该线程,可以将错误抛出到一个单独的线程中,一个使用setTimeout创建。因此我的解决方案(原来是Ivo Danihelka的一个阐述):

var startTime = (new Date()).getTime();
function logError(msg)
{
  var milliseconds = (new Date()).getTime() - startTime;
  window.setTimeout(function () {
    throw( new Error(milliseconds + ': ' + msg, "") );
  });
}
logError('testing');

我包括自开始时间以来的时间(以毫秒为单位),因为超时可能会使您可能希望看到消息的顺序发生偏差。

Error方法的第二个参数是文件名,这里是一个空字符串,以防止输出无用的文件名和行号。可以获得调用者函数,但不能以简单的浏览器独立方式。

如果我们能够显示带有警告或消息图标而不是错误图标的消息会很好,但我找不到办法来做到这一点。

使用throw的另一个问题是它可以被一个封闭的try-catch捕获并抛弃,并且将throw放在一个单独的线程中也可以避免这个障碍。但是,还有另一种方法可以捕获错误,即window.onerror处理程序被替换为执行不同操作的处理程序。无法帮助你。

答案 6 :(得分:9)

要真正回答这个问题:

console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);

您也可以使用信息,日志或警告而不是错误。

答案 7 :(得分:8)

如果您正在使用Firebug并且还需要支持IE,Safari或Opera,Firebug Lite会为这些浏览器添加console.log()支持。

答案 8 :(得分:5)

与往常一样,Internet Explorer是旱冰鞋中的大象,只需使用console.log()即可阻止您。

jQuery's log可以很容易地进行调整,但是不得不在任何地方添加它。如果你使用jQuery,一个解决方案是在最后将它放入你的jQuery文件中,首先缩小:

function log()
{
    if (arguments.length > 0)
    {
        // Join for graceful degregation
        var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, " ") : arguments[0];

        // This is the standard; Firebug and newer WebKit browsers support this.
        try {
            console.log(args);
            return true;
        } catch(e) {
            // Newer Opera browsers support posting erros to their consoles.
            try {
                opera.postError(args);
                return true;
            } 
            catch(e) 
            {
            }
        }

        // Catch all; a good old alert box.
        alert(args);
        return false;
    }
}

答案 9 :(得分:5)

关于上面提到的'throw()'的说明。它似乎完全停止了页面的执行(我在IE8中检查过),所以它对于记录“正在进行的进程”(比如跟踪某个变量......)并不是很有用。

我的建议可能是在文档中的某处添加 textarea 元素,并更改(或追加)其(这将更改其文本)以记录信息无论何时需要...

答案 10 :(得分:5)

WebKit Web Inspector还支持Firebug's控制台API(只是Dan's answer的一小部分内容)。

答案 11 :(得分:4)

访问https://developer.chrome.com/devtools/docs/console-api以获取完整的控制台API参考

    console.error(object[Obj,....])\

在这种情况下,对象将是您的错误字符串

答案 12 :(得分:3)

function foo() {
  function bar() {
    console.trace("Tracing is Done here");
  }
  bar();
}

foo();

console.log(console); //to print console object
console.clear('console.clear'); //to clear console
console.log('console.log'); //to print log message
console.info('console.info'); //to print log message 
console.debug('console.debug'); //to debug message
console.warn('console.warn'); //to print Warning
console.error('console.error'); //to print Error
console.table(["car", "fruits", "color"]);//to print data in table structure
console.assert('console.assert'); //to print Error
console.dir({"name":"test"});//to print object
console.dirxml({"name":"test"});//to print object as xml formate

To Print Error:- console.error('x=%d', x);

console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");

答案 13 :(得分:1)

console.log("your message here");

为我工作..我正在寻找这个......我使用的是Firefox。 这是我的剧本。

 $('document').ready(function() {
console.log('all images are loaded');
});

适用于Firefox和Chrome。

答案 14 :(得分:1)

最简单的方法是:

console.warn("Text to print on console");

答案 15 :(得分:0)

这不会打印到控制台,但会打开一个警告Popup,其中包含您的消息,这可能对某些调试很有用:

只是这样做:

alert("message");

答案 16 :(得分:0)

使用es6语法,您可以使用:

console.log(`x = ${x}`);

答案 17 :(得分:0)

要回答您的问题,您可以使用ES6功能

var var=10;
console.log(`var=${var}`);
相关问题