[javascript] 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);

This question is related to javascript debugging

The answer is


As always, Internet Explorer is the big elephant in rollerskates that stops you just simply using console.log().

jQuery's log can be adapted quite easily, but is a pain having to add it everywhere. One solution if you're using jQuery is to put it into your jQuery file at the end, minified first:

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

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

Usage:

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

This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:

just do:

alert("message");

With es6 syntax you can use:

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

The simplest way to do this is:

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

A note about 'throw()' mentioned above. It seems that it stops execution of the page completely (I checked in IE8) , so it's not very useful for logging "on going processes" (like to track a certain variable...)

My suggestion is perhaps to add a textarea element somewhere in your document and to change (or append to) its value (which would change its text) for logging information whenever needed...


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, "") );
  });
}
logError('testing');

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.


Visit https://developer.chrome.com/devtools/docs/console-api for a complete console api reference

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

In this case, object would be your error string


If you are using Firebug and need to support IE, Safari or Opera as well, Firebug Lite adds console.log() support to these browsers.


To actually answer the question:

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

Instead of error, you can also use info, log or warn.


console.log("your message here");

working for me.. i'm searching for this.. i used Firefox. here is my Script.

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

works in Firefox and Chrome.


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

_x000D_
_x000D_
console.log(console); //to print console object_x000D_
console.clear('console.clear'); //to clear console_x000D_
console.log('console.log'); //to print log message_x000D_
console.info('console.info'); //to print log message _x000D_
console.debug('console.debug'); //to debug message_x000D_
console.warn('console.warn'); //to print Warning_x000D_
console.error('console.error'); //to print Error_x000D_
console.table(["car", "fruits", "color"]);//to print data in table structure_x000D_
console.assert('console.assert'); //to print Error_x000D_
console.dir({"name":"test"});//to print object_x000D_
console.dirxml({"name":"test"});//to print object as xml formate
_x000D_
_x000D_
_x000D_

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

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


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


To answer your question you can use ES6 features,

var var=10;
console.log(`var=${var}`);

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

You also can add CSS to your logging messages:

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

If you use Safari, you can write

console.log("your message here");

and it appears right on the console of the browser.


The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).