When writing a complex web application one of the important debugging tools is using the logging facility the environment provides. This can help the developer see what's going in the application without interfering with the real UI.

The standard way to print a message to the JavaScript console of the web browser is using the log method of the console object. It accepts a list of strings and objects and prints them to the console.

Actually, the console object has several additional methods that can be used to fine-tune the logging. There debug, info, log, warn, error.

In our sample JavaScript code we use all 5 of them:

examples/javascript/logging/logging.js

function log_them() {
    console.debug("Calling console.debug");
    console.info("Calling console.info");
    console.log("Calling console.log");
    console.warn("Calling console.warn");
    console.error("Calling console.error");
}

log_them();

If you'd like to try the code, here is the HTML file that will load it including a link to the explanation on opening the JavaScript console in your favorite browser.

examples/javascript/logging/logging.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="logging.js"></script>
</head>
<body>
    <a href="http://code-maven.com/open-javascript-console" target="_blank">Open the JavaScript console</a> in order to see the logging messages.
</body>
</html>
Try!

If you don't want to try it now, you can check out these screenshots of the output:

In Chrome the various methods have different color and accompanying icon:

console logging in Chrome

In FireFox they are all the same color, but you still get a few icons:

console logging in FireFox

In both case, the right-hand side of the log-line displays the line number in the original file which makes it easier to understand which part of the code emitted the log message.