DEV Community

Cover image for An ultimate guide to Logging in JavaScript
devbookmark
devbookmark

Posted on • Originally published at devbookmark.com

An ultimate guide to Logging in JavaScript

In this post we'll also learn more about Logging in JavaScript. This post is for everyone who wants final guide to Logging in JavaScript.


The console is part of the window object that gives you access to the browser's console. It lets you output strings, arrays and objects that help debug your code.

We can get access to the console on one of two ways:

window.console.log("Hello World!"); 
console.log("I'm sammy"); 

// Hello World
// I'm sammy
Enter fullscreen mode Exit fullscreen mode

The most common element of the console object is console.log(). For most scenarios, you'll use it to get the job done.

There are four different ways of outputting a message to the console:

  • log

  • info

  • warn

  • error

Where console.error and console.warn out puts to stderr, the other output to stdout.


With the console object and its logging methods, long are the days of calling alert() to debug and get a variable's value.

Besides the general logging methods that we have discussed in the previous part, there are few more methods that we can play around with.

Now we will cover:

  • Stack tracing
  • Asserting

Stack tracing

The console.trace() method displays a trace that show how to code ended up at certain point.
Take a look at the below example, to understand how console.trace() works.

function hey(name) {
    console.trace('name:', name); 
    return `Hello ${name}!`; 
}
hey('sammy'); 

// OUTPUT
// "Hello sammy!"
Enter fullscreen mode Exit fullscreen mode

Asserting

The console.assert method is an easy way to run assertion tests. If the assertion of the 1st argument fails, the subsequent argument gets printed to the console.

Let's look at this example,

// this will pass, nothing will be logged
console.assert(1 == '1', '1 not == to "1"'); 
Enter fullscreen mode Exit fullscreen mode

The below assertion fails,

// this will pass, nothing will be logged
console.assert(1 === '1', '1 not == to "1"'); 
Enter fullscreen mode Exit fullscreen mode

Output:

Assertion failed: 1 not == to "1"
Enter fullscreen mode Exit fullscreen mode

Formatting Logs

There is a way to print out objects in a nice formatted way using console.dir().

For example:

const sammy = {
    topic: 'Logging', 
    platform: 'Javascript', 
    date: {
        year: '2020', 
        month: 'March', 
        day: 'Saturday'
    }
}; 

console.dir(sammy); 
Enter fullscreen mode Exit fullscreen mode

You can print out a DOM element's markup in a formatted way using console.dirxml().

for example:

<body>
   <h1>Hey</h1>

   <script>
      console.dirxml(document.body)
   </script>
</body>   
Enter fullscreen mode Exit fullscreen mode

The same will be the output 😅

Countings

The console.count() method is used to count the number of times it has been invokedd with the same provided label.

For example, here we have two counter, one for even values and another on for odd values.

[1, 2, 3, 4, 5].forEach(nb => {
    if (nb % 2 === 0) {
        console.count('even'); 
    } else {
        console.count('odd'); 
    }
}); 
Enter fullscreen mode Exit fullscreen mode

Clearing the logs:

You can clear out all the console logs using the console.clear() method.


Record Timings

You can record how long an operation took to complete using console. You can start a timer with console.time and then end it with console.endTime.

For Example:

console.time('timer'); 
setTimeout(() => console.log, 1000); 
console.timeEnd('timer'); 

// timer: 0.123945114ms
Enter fullscreen mode Exit fullscreen mode

Note: Passing the label in console.time is optional. If you use a label with console.time you must pass-in that same label when calling console.timeEnd.

Grouping logs

You can group the console messages together with console. Use console.group and console.groupEnd to group console messages together.

For Example:

console.group('Even Numbers'); 
console.log(2); 
console.log(4); 
console.log(6); 
console.groupEnd('Even Numbers'); 
Enter fullscreen mode Exit fullscreen mode

Nested grouping logs

Groups ca also be nested to another one. Take a look at the below example,

console.group('Even'); 
console.log('2'); 
console.group('Odd'); 
console.log('1'); 
console.log('2'); 
console.groupEnd(); 
console.log('6'); 
console.groupEnd(); 
Enter fullscreen mode Exit fullscreen mode

Styling your logs:

Console logging can be styled using the delimiter %c. The first argument is the message to displayed. Everything that comes after the first %c will be styled by the string provided by the secong argument, then everything after the next %c is styled by the following string argumnet, and so on.

console.log(
    'Hello %csammy%c!', 
    'color: blue; font-weight: bold; font-size: 1rem;', 
    'color: hotpink; font-weight: bold; font-size: 1rem;'
); 
Enter fullscreen mode Exit fullscreen mode

Tabular visualization of logs

The console.table() allows to display data in the console in a nice tabular format.

const jsonData = [
    {
        color: "red", 
        value: "#f00"
    }, 
    {
        color: "green", 
        value: "#0f0"
    }, 
    {
        color: "blue", 
        value: "#00f"
    }
]; 

console.table(jsonData); 
Enter fullscreen mode Exit fullscreen mode

Any type of JSON can be represented in a tabular view. You can display an Array in a tabular view

const y = [
    ["One", "Two"], 
    ["Three", "Four"]
]; 
Enter fullscreen mode Exit fullscreen mode

And, you can also display an object in a tabular view. You may wonder how? Take a look at this example.

const x = { a: 1, v: { a: 1 } }; 
Enter fullscreen mode Exit fullscreen mode

console.table() displays nay object data in a tabular view. But, if a JSON has multiple nested objects inside, it just prints the root level objects in the tabular view.

Let's see that in this example:

const x = [
    { p: 123, i: 1 }, 
    {
        p: 124, 
        i: 2, 
        x: {
            a: 1, 
            b: { s: 23 }
        }
    }
];
Enter fullscreen mode Exit fullscreen mode

Sorting in logs

console.table() comes with an inbuilt sorting. Yoou can sort the table by a particular column by clicking on that column's label.

const y = [
    ["One", "Two"], 
    ["Three", "Four"]
]; 

console.table(y); 
Enter fullscreen mode Exit fullscreen mode


⚡Thanks For Reading | Happy Coding🚀

Top comments (0)