459

How can I print a message to the error console, preferably including a variable?

For example, something like:

print('x=%d', x);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
  • 9
    Which console are you talking about. Browser console or JavaScript framework specific console? – Eric Schoonover Oct 02 '08 at 20:27
  • Related post - [Chrome: console.log, console.debug are not working](https://stackoverflow.com/q/18760213/465053) – RBT May 31 '18 at 09:16

18 Answers18

477

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

Community
  • 1
  • 1
Dan
  • 61,568
  • 9
  • 61
  • 78
  • Unfortunately, this will cause an error in IE though. So you have to comment it out before deployment, or include a library that traps it. http://getfirebug.com/lite.html – Shermozle Oct 03 '08 at 03:31
  • 16
    @Dan: The WebKit Web Inspector also supports the FireBug console API – olliej Oct 03 '08 at 03:45
  • 169
    why is this the accepted answer? he didn't ask how to write to the firebug console, he asked how to write to the error console. not being a dick or anything, just pointing it out. – matt lohkamp Oct 03 '08 at 10:25
  • 131
    +1. And for the benefit of anyone arriving at this question now, it's worth pointing out that since the question was answered, all browsers have now implemented the console object, so `console.log()` etc should work in all browsers, including IE. However, in all cases, you need to have the debugger window open at the time, otherwise calls to `console` will generate errors. – Spudley Feb 10 '11 at 14:59
  • 2
    @andrewjackson as noted earlier, console.log works fine in all modern browsers, including IE. Your code is still perfectly valid and useful if you intend to support older browsers (and if you're working on a public website, you sure as heck should!), however my criticism is only that your comment is misleading / not accurate. – BrainSlugs83 Jun 29 '12 at 04:42
  • 1
    console.debug() on the other hand doesn't exist in in IE. We can work around that with: if (!console.debug){ console.debug = function(args){ console.log(args); } } – Rovanion Nov 26 '12 at 10:12
343
console.error(message); // Outputs an error message to the Web Console
console.log(message); // Outputs a message to the Web Console
console.warn(message); // Outputs a warning message to the Web Console
console.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small "i" in front of the message.

You also can add CSS:

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

More info can be found here: https://developer.mozilla.org/en-US/docs/Web/API/console

Nicholas
  • 5,430
  • 3
  • 21
  • 21
86

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');
Paul Richter
  • 10,908
  • 10
  • 52
  • 85
Ivo Danihelka
  • 3,382
  • 3
  • 31
  • 27
54

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ian Oxley
  • 10,916
  • 6
  • 42
  • 49
  • 7
    throw() is a great suggestion - this should be the chosen answer. – matt lohkamp Oct 03 '08 at 10:24
  • 1
    Yeah, it's cross-browser and it does the job. Upped. – ArtBIT Oct 25 '10 at 02:00
  • 17
    Agreed, this is one cross-browser approach. But.. Isn't throwing an exception fundamentally different from logging messages? – Robin Maben Dec 08 '10 at 06:59
  • 1
    Throwing an exception won't necessarily work if there is any try...catch that is wrapping the throw. (This could be anywhere above in the dynamic stack, not necessarily visibly, lexically wrapping the throw.) The catch could gobble up the throw, and maybe report something, or maybe not. Sometimes libraries will "helpfully" ignore errors in parts of a page to allow the rest of the page to render. – dlaliberte Jan 27 '11 at 21:03
  • 14
    On the other hand, throwing an exception will stop the execution of the current "thread" (as noted by Yuval A), and resume it in the catch if there is one. I doubt this is what is desired. – dlaliberte Jan 27 '11 at 21:11
  • 8
    `throw()` is definitely not the way to do this. you'll get in trouble sooner or later. for me it was sooner :( – Hugo Mota Jun 30 '11 at 20:06
  • 4
    @Ian_Oxley: it was down at some point, now it's back up, but posting the code right here is still better, and recommended by stackoverflow best practices. – scrat.squirrel Mar 19 '12 at 15:21
15

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.

dlaliberte
  • 3,250
  • 2
  • 25
  • 22
15

If you use Safari, you can write

console.log("your message here");

and it appears right on the console of the browser.

Lukas
  • 175
  • 1
  • 2
10

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.

Yster
  • 3,147
  • 5
  • 32
  • 48
  • Your answer seems best, but [Mozilla's MDN page](https://developer.mozilla.org/en-US/docs/Web/API/Console/error) says `console.error(..)` is a non-standard feature and should not be used in production. What is your take on this? Do you have any suggestions for a novice programmer using `console.error` vs `console.log`? – modulitos Feb 27 '15 at 21:27
  • This is interesting. We shouldn't use this then. Thanks for the info, Lucas. – Yster Mar 13 '15 at 15:18
  • 2
    [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) deems `console.log(...)` "non-standard" as well. In that regard, `console.error` is as stable as `console.log`. – Mike Rapadas May 07 '15 at 14:29
  • 1
    @Lucas Who cares if it's standard? Who's going to use console logging for production? – Andrew May 02 '17 at 19:05
  • 1
    Console.error works now in all major browsers. Even IE8. See https://developer.mozilla.org/en-US/docs/Web/API/Console/error – Red Sep 25 '17 at 15:01
8

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

Devon
  • 5,786
  • 5
  • 38
  • 46
6

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

Community
  • 1
  • 1
olliej
  • 35,755
  • 9
  • 58
  • 55
5

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...

Yuval A.
  • 5,849
  • 11
  • 51
  • 63
  • I'm guessing it's because you didn't answer the OP's question. To print to the JS console, you must use a built-in method like `console.log()`, `throw()`, etc. In addition, there is nothing wrong with the behavior of `throw()` as you seem to imply - the fact that it stops execution is intentional and documented (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw), and it's consistent with how exceptions are thrown/caught in other programming languages. (If you want to log the contents of a variable without stopping execution, that's what `console.log()` is for.) – Sean the Bean Sep 11 '15 at 19:41
  • @SeantheBean, originally there was a discussion about the fact that IE didn't support `console.log` - so people were giving alternatives. About `throw()` stopping execution, *of-course* it's intentional, nobody said it's not. That's why it's usually *not* a good way to log debug information in runtime, which what the OP wanted... – Yuval A. Nov 17 '15 at 15:17
5

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;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris S
  • 64,770
  • 52
  • 221
  • 239
  • It's now accepted as jQuery's extensions, but wouldn't it be efficienter to check if 'console' and 'opera' objects exist before catching exception? – Danubian Sailor Nov 14 '11 at 09:20
  • @lechlukasz I think you can save the overhead of the extension and just use console.log plus this IE check: http://stackoverflow.com/questions/1215392/how-to-quickly-and-conveniently-disable-all-console-log-statements-in-my-code/6076286#6076286 – Chris S Nov 14 '11 at 17:26
4

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

devSouth555
  • 121
  • 1
  • 5
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");
Parth Raval
  • 4,097
  • 3
  • 23
  • 36
1
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.

D.K
  • 41
  • 1
  • 7
1

The simplest way to do this is:

console.warn("Text to print on console");
Pang
  • 9,564
  • 146
  • 81
  • 122
1

To answer your question you can use ES6 features,

var var=10;
console.log(`var=${var}`);
Aniket Kulkarni
  • 1,985
  • 2
  • 17
  • 22
0

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");
mmm
  • 689
  • 2
  • 12
  • 25
0

With es6 syntax you can use:

console.log(`x = ${x}`);
jkordas
  • 155
  • 6