JavaScript: How do I print a message to the error console?

JavaScript: How do I print a message to the error console?

How can I print a message to the error console, preferably including a variable?
For example, something like:
print(‘x=%d’, x);


Solution 1:

Install Firebug and then you can use console.log(...) and console.debug(...), etc. (see the documentation for more).

Solution 2:

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; //gives an info message with an 'i' in front of the message

You also can add CSS to your logging messages:

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

Solution 3:

Exceptions are logged into the JavaScript console. You can use that if you want to keep Firebug disabled.

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


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

Solution 4:

One good way to do this that works cross-browser is outlined in Debugging JavaScript: Throw Away Your Alerts!.

Solution 5:

If you use Safari, you can write

console.log("your message here");

and it appears right on the console of the browser.

Solution 6:

Here is a solution to the literal question of how to print a message to the browser’s error console, not the debugger console. (There might be good reasons to bypass the debugger.)

As I noted in comments about the suggestion to throw an error to get a message in the error console, one problem is that this will interrupt the thread of execution. If you don’t want to interrupt the thread, you can throw the error in a separate thread, one created using setTimeout. Hence my solution (which turns out to be an elaboration of the one by Ivo Danihelka):

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

I include the time in milliseconds since the start time because the timeout could skew the order in which you might expect to see the messages.

The second argument to the Error method is for the filename, which is an empty string here to prevent output of the useless filename and line number. It is possible to get the caller function but not in a simple browser independent way.

It would be nice if we could display the message with a warning or message icon instead of the error icon, but I can’t find a way to do that.

Another problem with using throw is that it could be caught and thrown away by an enclosing try-catch, and putting the throw in a separate thread avoids that obstacle as well. However, there is yet another way the error could be caught, which is if the window.onerror handler is replaced with one that does something different. Can’t help you there.