如何在谷歌Chrome JavaScript控制台打印调试消息?

时间:2022-12-27 20:47:07

How do I print debug messages in the Google Chrome JavaScript Console?

如何在谷歌Chrome JavaScript控制台打印调试消息?

Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the print command in JavaScript Debugger will not work here. In the JavaScript Console, print() will send the parameter to the printer.

请注意,JavaScript控制台与JavaScript调试器不同;它们有不同的语法,所以JavaScript调试器中的print命令在这里不能工作。在JavaScript控制台中,print()将把参数发送给打印机。

14 个解决方案

#1


571  

Executing following code from the browser address bar:

从浏览器地址栏执行以下代码:

javascript: console.log(2);

successfully prints message to the "JavaScript Console" in Google Chrome.

成功将消息打印到谷歌Chrome中的“JavaScript控制台”。

#2


164  

Improving on Andru's idea, you can write a script which creates console functions if they don't exist:

改进Andru的想法,你可以编写一个脚本,创建控制台功能,如果它们不存在:

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};

Then, use any of the following:

然后,使用下列任何一种:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.

这些函数将记录不同类型的项目(可以基于日志、信息、错误或警告进行过滤),并且在没有控制台时不会导致错误。这些功能将适用于Firebug和Chrome控制台。

#3


42  

Just add a cool feature which a lot of developers miss:

只要添加一个很多开发人员都没有的酷特性:

console.log("this is %o, event is %o, host is %s", this, e, location.host);

This is the magical %o dump clickable and deep-browsable content of a JavaScript object. %s was shown just for a record.

这是一个不可思议的JavaScript对象的%o转储可点击和可深入浏览的内容。%s仅显示为一个记录。

Also this is cool too:

这也很酷:

console.log("%s", new Error().stack);

Which gives a Java-like stack trace to the point of the new Error() invocation (including path to file and line number!).

它向新Error()调用的点(包括文件的路径和行号!)提供类似java的堆栈跟踪。

Both %o and new Error().stack are available in Chrome and Firefox!

%o和新错误()。在Chrome和Firefox中可以使用堆栈!

Also for stack traces in Firefox use:

对于Firefox中使用的堆栈跟踪:

console.trace();

As https://developer.mozilla.org/en-US/docs/Web/API/console says.

像https://developer.mozilla.org/en-US/docs/Web/API/console说。

Happy hacking!

黑客快乐!

UPDATE: Some libraries are written by bad people which redefine the console object for their own purposes. To restore the original browser console after loading library, use:

更新:有些库是由坏人编写的,他们为自己的目的重新定义控制台对象。要在加载库后恢复原来的浏览器控制台,请使用:

delete console.log;
delete console.warn;
....

See Stack Overflow question Restoring console.log().

请参阅恢复console.log()的堆栈溢出问题。

#4


16  

Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.

只是一个简短的警告——如果您想在Internet Explorer中测试而不删除所有console.log()的,那么您将需要使用Firebug Lite,否则您将得到一些不太友好的错误。

(Or create your own console.log() which just returns false.)

(或者创建自己的console.log(),它只返回false。)

#5


16  

Here is a short script which checks if the console is available. If it is not, it tries to load Firebug and if Firebug is not available it loads Firebug Lite. Now you can use console.log in any browser. Enjoy!

下面是一个简短的脚本,它检查控制台是否可用。如果不是,则尝试加载Firebug,如果Firebug不可用,则加载Firebug Lite。现在可以使用控制台了。任何浏览器登录。享受吧!

if (!window['console']) {

    // Enable console
    if (window['loadFirebugConsole']) {
        window.loadFirebugConsole();
    }
    else {
        // No console, use Firebug Lite
        var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) {
            if (F.getElementById(b))
                return;
            E = F[i+'NS']&&F.documentElement.namespaceURI;
            E = E ? F[i + 'NS'](E, 'script') : F[i]('script');
            E[r]('id', b);
            E[r]('src', I + g + T);
            E[r](b, u);
            (F[e]('head')[0] || F[e]('body')[0]).appendChild(E);
            E = new Image;
            E[r]('src', I + L);
        };
        firebugLite(
            document, 'createElement', 'setAttribute', 'getElementsByTagName',
            'FirebugLite', '4', 'firebug-lite.js',
            'releases/lite/latest/skin/xp/sprite.png',
            'https://getfirebug.com/', '#startOpened');
    }
}
else {
    // Console is already available, no action needed.
}

#6


13  

In addition to Delan Azabani's answer, I like to share my console.js, and I use for the same purpose. I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet Explorer, which has a console.log function, but no console.debug:

除了Delan Azabani的回答,我还想分享我的控制台。js,我使用它的目的是一样的。我使用一个函数名数组创建了一个noop控制台,在我看来这是一种非常方便的方式,我负责Internet Explorer,它有一个控制台。日志功能,但没有console.debug:

// Create a noop console object if the browser doesn't provide one...
if (!window.console){
  window.console = {};
}

// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
  if (!window.console.debug && typeof window.console.log !== 'undefined') {
    window.console.debug = window.console.log;
  }
}

// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

for (var i = 0; i < names.length; ++i){
  if(!window.console[names[i]]){
    window.console[names[i]] = function() {};
  }
}

#7


11  

Or use this function:

或使用这个函数:

function log(message){
    if (typeof console == "object") {
        console.log(message);
    }
}

#8


6  

Here's my console wrapper class. It gives me scope output as well to make life easier. Note the use of localConsole.debug.call() so that localConsole.debug runs in the scope of the calling class, providing access to its toString method.

这是我的控制台包装类。它还为我提供了范围输出,使我的生活更容易。注意使用localConsole.debug.call(),使localConsole.debug在调用类的范围内运行,提供对其toString方法的访问。

localConsole = {

    info: function(caller, msg, args) {
        if ( window.console && window.console.info ) {
            var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
            if (args) {
                params = params.concat(args);
            }
            console.info.apply(console, params);
        }
    },

    debug: function(caller, msg, args) {
        if ( window.console && window.console.debug ) {
            var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
            if (args) {
                params = params.concat(args);
            }
            console.debug.apply(console, params);
        }
    }
};

someClass = {

    toString: function(){
        return 'In scope of someClass';
    },

    someFunc: function() {

        myObj = {
            dr: 'zeus',
            cat: 'hat'
        };

        localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);
    }
};

someClass.someFunc();

This gives output like so in Firebug:

这在Firebug中给出了如下输出:

In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}

Or Chrome:

或铬:

In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object

#9


5  

Personally I use this, which is similar to tarek11011's:

我个人使用这个,类似于tarek11011:

// Use a less-common namespace than just 'log'
function myLog(msg)
{
    // Attempt to send a message to the console
    try
    {
        console.log(msg);
    }
    // Fail gracefully if it does not exist
    catch(e){}
}

The main point is that it's a good idea to at least have some practice of logging other than just sticking console.log() right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.

的主要观点是,这是一个好主意,至少有一些实践的日志除了坚持console.log()到您的JavaScript代码,因为如果你忘掉它,生产站点,它可以打破所有的JavaScript代码页。

#10


4  

You could use console.log() if you have a debugged code in what programming software editor you have and you will see the output mostly likely the best editor for me (Google Chrome). Just press F12 and press the Console tab. You will see the result. Happy coding. :)

如果您拥有的编程软件编辑器中有经过调试的代码,您可以使用console.log(),并且您将看到输出结果很可能是我的最佳编辑器(谷歌Chrome)。只需按F12并按控制台选项卡。你会看到结果。快乐的编码。:)

#11


4  

I've had a lot of issues with developers checking in their console.() statements. And, I really don't like debugging Internet Explorer, despite the fantastic improvements of Internet Explorer 10 and Visual Studio 2012, etc.

在开发人员检查他们的控制台.()语句时,我遇到了很多问题。而且,我真的不喜欢调试Internet Explorer,尽管Internet Explorer 10和Visual Studio 2012有了很大的改进,等等。

So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. I also added console.() functions to Internet Explorer (that displays an alert() instead).

因此,我重写了控制台对象本身……我添加了一个__localhost标志,它只允许在localhost上的控制台语句。我还添加了console.()函数到Internet Explorer(它显示一个alert()))。

// Console extensions...
(function() {
    var __localhost = (document.location.host === "localhost"),
        __allow_examine = true;

    if (!console) {
        console = {};
    }

    console.__log = console.log;
    console.log = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__log === "function") {
                console.__log(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__info = console.info;
    console.info = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__info === "function") {
                console.__info(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__warn = console.warn;
    console.warn = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__warn === "function") {
                console.__warn(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__error = console.error;
    console.error = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__error === "function") {
                console.__error(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__group = console.group;
    console.group = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__group === "function") {
                console.__group(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert("group:\r\n" + msg + "{");
            }
        }
    };

    console.__groupEnd = console.groupEnd;
    console.groupEnd = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__groupEnd === "function") {
                console.__groupEnd(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg + "\r\n}");
            }
        }
    };

    /// <summary>
    /// Clever way to leave hundreds of debug output messages in the code,
    /// but not see _everything_ when you only want to see _some_ of the
    /// debugging messages.
    /// </summary>
    /// <remarks>
    /// To enable __examine_() statements for sections/groups of code, type the
    /// following in your browser's console:
    ///       top.__examine_ABC = true;
    /// This will enable only the console.examine("ABC", ... ) statements
    /// in the code.
    /// </remarks>
    console.examine = function() {
        if (!__allow_examine) {
            return;
        }
        if (arguments.length > 0) {
            var obj = top["__examine_" + arguments[0]];
            if (obj && obj === true) {
                console.log(arguments.splice(0, 1));
            }
        }
    };
})();

Example use:

使用示例:

    console.log("hello");

Chrome/Firefox:

Chrome和Firefox:

    prints hello in the console window.

Internet Explorer:

Internet Explorer:

    displays an alert with 'hello'.

For those who look closely at the code, you'll discover the console.examine() function. I created this years ago so that I can leave debug code in certain areas around the product to help troubleshoot QA/customer issues. For instance, I would leave the following line in some released code:

对于那些仔细查看代码的人,您将发现console.examined()函数。我是在几年前创建的,所以我可以将调试代码放在产品的某些区域,以帮助解决QA/客户问题。例如,我会在一些发布的代码中留下以下一行:

    function doSomething(arg1) {
        // ...
        console.examine("someLabel", arg1);
        // ...
    }

And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'):

然后从发布的产品中,在控制台(或以'javascript:'为前缀的地址栏)输入以下内容:

    top.__examine_someLabel = true;

Then, I will see all of the logged console.examine() statements. It's been a fantastic help many times over.

然后,我将看到所有已登录的控制台。检查()语句。这是一个神奇的帮助很多次。

#12


3  

Simple Internet Explorer 7 and below shim that preserves line numbering for other browsers:

简单的Internet Explorer 7和以下的shim,为其他浏览器保留行号:

/* Console shim */
(function () {
    var f = function () {};
    if (!window.console) {
        window.console = {
            log:f, info:f, warn:f, debug:f, error:f
        };
    }
}());

#13


2  

console.debug("");

Using this method prints out the text in a bright blue color in the console.

使用此方法,可以在控制台以亮蓝色打印文本。

如何在谷歌Chrome JavaScript控制台打印调试消息?

#14


1  

Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....

进一步改进Delan和Andru的想法(这就是为什么这个答案是经过编辑的版本);控制台。日志可能同时存在其他功能可能不会,所以默认映射到相同的函数作为console.log ....

You can write a script which creates console functions if they don't exist:

如果控制台功能不存在,您可以编写脚本创建控制台功能:

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || console.log;  // defaults to log
console.error = console.error || console.log; // defaults to log
console.info = console.info || console.log; // defaults to log

Then, use any of the following:

然后,使用下列任何一种:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.

这些函数将记录不同类型的项目(可以基于日志、信息、错误或警告进行过滤),并且在没有控制台时不会导致错误。这些功能将适用于Firebug和Chrome控制台。

#1


571  

Executing following code from the browser address bar:

从浏览器地址栏执行以下代码:

javascript: console.log(2);

successfully prints message to the "JavaScript Console" in Google Chrome.

成功将消息打印到谷歌Chrome中的“JavaScript控制台”。

#2


164  

Improving on Andru's idea, you can write a script which creates console functions if they don't exist:

改进Andru的想法,你可以编写一个脚本,创建控制台功能,如果它们不存在:

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};

Then, use any of the following:

然后,使用下列任何一种:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.

这些函数将记录不同类型的项目(可以基于日志、信息、错误或警告进行过滤),并且在没有控制台时不会导致错误。这些功能将适用于Firebug和Chrome控制台。

#3


42  

Just add a cool feature which a lot of developers miss:

只要添加一个很多开发人员都没有的酷特性:

console.log("this is %o, event is %o, host is %s", this, e, location.host);

This is the magical %o dump clickable and deep-browsable content of a JavaScript object. %s was shown just for a record.

这是一个不可思议的JavaScript对象的%o转储可点击和可深入浏览的内容。%s仅显示为一个记录。

Also this is cool too:

这也很酷:

console.log("%s", new Error().stack);

Which gives a Java-like stack trace to the point of the new Error() invocation (including path to file and line number!).

它向新Error()调用的点(包括文件的路径和行号!)提供类似java的堆栈跟踪。

Both %o and new Error().stack are available in Chrome and Firefox!

%o和新错误()。在Chrome和Firefox中可以使用堆栈!

Also for stack traces in Firefox use:

对于Firefox中使用的堆栈跟踪:

console.trace();

As https://developer.mozilla.org/en-US/docs/Web/API/console says.

像https://developer.mozilla.org/en-US/docs/Web/API/console说。

Happy hacking!

黑客快乐!

UPDATE: Some libraries are written by bad people which redefine the console object for their own purposes. To restore the original browser console after loading library, use:

更新:有些库是由坏人编写的,他们为自己的目的重新定义控制台对象。要在加载库后恢复原来的浏览器控制台,请使用:

delete console.log;
delete console.warn;
....

See Stack Overflow question Restoring console.log().

请参阅恢复console.log()的堆栈溢出问题。

#4


16  

Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.

只是一个简短的警告——如果您想在Internet Explorer中测试而不删除所有console.log()的,那么您将需要使用Firebug Lite,否则您将得到一些不太友好的错误。

(Or create your own console.log() which just returns false.)

(或者创建自己的console.log(),它只返回false。)

#5


16  

Here is a short script which checks if the console is available. If it is not, it tries to load Firebug and if Firebug is not available it loads Firebug Lite. Now you can use console.log in any browser. Enjoy!

下面是一个简短的脚本,它检查控制台是否可用。如果不是,则尝试加载Firebug,如果Firebug不可用,则加载Firebug Lite。现在可以使用控制台了。任何浏览器登录。享受吧!

if (!window['console']) {

    // Enable console
    if (window['loadFirebugConsole']) {
        window.loadFirebugConsole();
    }
    else {
        // No console, use Firebug Lite
        var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) {
            if (F.getElementById(b))
                return;
            E = F[i+'NS']&&F.documentElement.namespaceURI;
            E = E ? F[i + 'NS'](E, 'script') : F[i]('script');
            E[r]('id', b);
            E[r]('src', I + g + T);
            E[r](b, u);
            (F[e]('head')[0] || F[e]('body')[0]).appendChild(E);
            E = new Image;
            E[r]('src', I + L);
        };
        firebugLite(
            document, 'createElement', 'setAttribute', 'getElementsByTagName',
            'FirebugLite', '4', 'firebug-lite.js',
            'releases/lite/latest/skin/xp/sprite.png',
            'https://getfirebug.com/', '#startOpened');
    }
}
else {
    // Console is already available, no action needed.
}

#6


13  

In addition to Delan Azabani's answer, I like to share my console.js, and I use for the same purpose. I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet Explorer, which has a console.log function, but no console.debug:

除了Delan Azabani的回答,我还想分享我的控制台。js,我使用它的目的是一样的。我使用一个函数名数组创建了一个noop控制台,在我看来这是一种非常方便的方式,我负责Internet Explorer,它有一个控制台。日志功能,但没有console.debug:

// Create a noop console object if the browser doesn't provide one...
if (!window.console){
  window.console = {};
}

// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
  if (!window.console.debug && typeof window.console.log !== 'undefined') {
    window.console.debug = window.console.log;
  }
}

// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

for (var i = 0; i < names.length; ++i){
  if(!window.console[names[i]]){
    window.console[names[i]] = function() {};
  }
}

#7


11  

Or use this function:

或使用这个函数:

function log(message){
    if (typeof console == "object") {
        console.log(message);
    }
}

#8


6  

Here's my console wrapper class. It gives me scope output as well to make life easier. Note the use of localConsole.debug.call() so that localConsole.debug runs in the scope of the calling class, providing access to its toString method.

这是我的控制台包装类。它还为我提供了范围输出,使我的生活更容易。注意使用localConsole.debug.call(),使localConsole.debug在调用类的范围内运行,提供对其toString方法的访问。

localConsole = {

    info: function(caller, msg, args) {
        if ( window.console && window.console.info ) {
            var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
            if (args) {
                params = params.concat(args);
            }
            console.info.apply(console, params);
        }
    },

    debug: function(caller, msg, args) {
        if ( window.console && window.console.debug ) {
            var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
            if (args) {
                params = params.concat(args);
            }
            console.debug.apply(console, params);
        }
    }
};

someClass = {

    toString: function(){
        return 'In scope of someClass';
    },

    someFunc: function() {

        myObj = {
            dr: 'zeus',
            cat: 'hat'
        };

        localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);
    }
};

someClass.someFunc();

This gives output like so in Firebug:

这在Firebug中给出了如下输出:

In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}

Or Chrome:

或铬:

In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object

#9


5  

Personally I use this, which is similar to tarek11011's:

我个人使用这个,类似于tarek11011:

// Use a less-common namespace than just 'log'
function myLog(msg)
{
    // Attempt to send a message to the console
    try
    {
        console.log(msg);
    }
    // Fail gracefully if it does not exist
    catch(e){}
}

The main point is that it's a good idea to at least have some practice of logging other than just sticking console.log() right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.

的主要观点是,这是一个好主意,至少有一些实践的日志除了坚持console.log()到您的JavaScript代码,因为如果你忘掉它,生产站点,它可以打破所有的JavaScript代码页。

#10


4  

You could use console.log() if you have a debugged code in what programming software editor you have and you will see the output mostly likely the best editor for me (Google Chrome). Just press F12 and press the Console tab. You will see the result. Happy coding. :)

如果您拥有的编程软件编辑器中有经过调试的代码,您可以使用console.log(),并且您将看到输出结果很可能是我的最佳编辑器(谷歌Chrome)。只需按F12并按控制台选项卡。你会看到结果。快乐的编码。:)

#11


4  

I've had a lot of issues with developers checking in their console.() statements. And, I really don't like debugging Internet Explorer, despite the fantastic improvements of Internet Explorer 10 and Visual Studio 2012, etc.

在开发人员检查他们的控制台.()语句时,我遇到了很多问题。而且,我真的不喜欢调试Internet Explorer,尽管Internet Explorer 10和Visual Studio 2012有了很大的改进,等等。

So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. I also added console.() functions to Internet Explorer (that displays an alert() instead).

因此,我重写了控制台对象本身……我添加了一个__localhost标志,它只允许在localhost上的控制台语句。我还添加了console.()函数到Internet Explorer(它显示一个alert()))。

// Console extensions...
(function() {
    var __localhost = (document.location.host === "localhost"),
        __allow_examine = true;

    if (!console) {
        console = {};
    }

    console.__log = console.log;
    console.log = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__log === "function") {
                console.__log(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__info = console.info;
    console.info = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__info === "function") {
                console.__info(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__warn = console.warn;
    console.warn = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__warn === "function") {
                console.__warn(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__error = console.error;
    console.error = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__error === "function") {
                console.__error(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__group = console.group;
    console.group = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__group === "function") {
                console.__group(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert("group:\r\n" + msg + "{");
            }
        }
    };

    console.__groupEnd = console.groupEnd;
    console.groupEnd = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__groupEnd === "function") {
                console.__groupEnd(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg + "\r\n}");
            }
        }
    };

    /// <summary>
    /// Clever way to leave hundreds of debug output messages in the code,
    /// but not see _everything_ when you only want to see _some_ of the
    /// debugging messages.
    /// </summary>
    /// <remarks>
    /// To enable __examine_() statements for sections/groups of code, type the
    /// following in your browser's console:
    ///       top.__examine_ABC = true;
    /// This will enable only the console.examine("ABC", ... ) statements
    /// in the code.
    /// </remarks>
    console.examine = function() {
        if (!__allow_examine) {
            return;
        }
        if (arguments.length > 0) {
            var obj = top["__examine_" + arguments[0]];
            if (obj && obj === true) {
                console.log(arguments.splice(0, 1));
            }
        }
    };
})();

Example use:

使用示例:

    console.log("hello");

Chrome/Firefox:

Chrome和Firefox:

    prints hello in the console window.

Internet Explorer:

Internet Explorer:

    displays an alert with 'hello'.

For those who look closely at the code, you'll discover the console.examine() function. I created this years ago so that I can leave debug code in certain areas around the product to help troubleshoot QA/customer issues. For instance, I would leave the following line in some released code:

对于那些仔细查看代码的人,您将发现console.examined()函数。我是在几年前创建的,所以我可以将调试代码放在产品的某些区域,以帮助解决QA/客户问题。例如,我会在一些发布的代码中留下以下一行:

    function doSomething(arg1) {
        // ...
        console.examine("someLabel", arg1);
        // ...
    }

And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'):

然后从发布的产品中,在控制台(或以'javascript:'为前缀的地址栏)输入以下内容:

    top.__examine_someLabel = true;

Then, I will see all of the logged console.examine() statements. It's been a fantastic help many times over.

然后,我将看到所有已登录的控制台。检查()语句。这是一个神奇的帮助很多次。

#12


3  

Simple Internet Explorer 7 and below shim that preserves line numbering for other browsers:

简单的Internet Explorer 7和以下的shim,为其他浏览器保留行号:

/* Console shim */
(function () {
    var f = function () {};
    if (!window.console) {
        window.console = {
            log:f, info:f, warn:f, debug:f, error:f
        };
    }
}());

#13


2  

console.debug("");

Using this method prints out the text in a bright blue color in the console.

使用此方法,可以在控制台以亮蓝色打印文本。

如何在谷歌Chrome JavaScript控制台打印调试消息?

#14


1  

Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....

进一步改进Delan和Andru的想法(这就是为什么这个答案是经过编辑的版本);控制台。日志可能同时存在其他功能可能不会,所以默认映射到相同的函数作为console.log ....

You can write a script which creates console functions if they don't exist:

如果控制台功能不存在,您可以编写脚本创建控制台功能:

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || console.log;  // defaults to log
console.error = console.error || console.log; // defaults to log
console.info = console.info || console.log; // defaults to log

Then, use any of the following:

然后,使用下列任何一种:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.

这些函数将记录不同类型的项目(可以基于日志、信息、错误或警告进行过滤),并且在没有控制台时不会导致错误。这些功能将适用于Firebug和Chrome控制台。