An ultimate guide to Logging in JavaScript
Tags: javascript, webdev, programming, guide
Published: 2021-08-26 07:54:52

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: 
```js
window.console.log("Hello World!"); 
console.log("I'm sammy"); 

// Hello World
// I'm sammy
```

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  
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616817742750/8SxL44ciq.png?auto=compress">

- info  
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616817783335/YTt8A_xkn.png?auto=compress">

- warn   
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616817843829/hqFKPVqpu.png?auto=compress">

- error 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616817870907/OW1ekLUb3.png?auto=compress">

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. 

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

// OUTPUT
// "Hello sammy!"
```

### 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, 

```js
// this will pass, nothing will be logged
console.assert(1 == '1', '1 not == to "1"'); 
```
The below assertion fails, 

```js
// this will pass, nothing will be logged
console.assert(1 === '1', '1 not == to "1"'); 
```

Output: 

```js
Assertion failed: 1 not == to "1"
```

--- 

## Formatting Logs

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

For example: 

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

console.dir(sammy); 
```

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616819016518/fbHExT-rb.png?auto=compress">

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

for example: 

```html
<body>
   <h1>Hey</h1>

   <script>
      console.dirxml(document.body)
   </script>
</body>   
```

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. 

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

#### 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: 

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

// timer: 0.123945114ms
```

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: 

```js
console.group('Even Numbers'); 
console.log(2); 
console.log(4); 
console.log(6); 
console.groupEnd('Even Numbers'); 
```

<img>

### Nested grouping logs 

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

```js
console.group('Even'); 
console.log('2'); 
console.group('Odd'); 
console.log('1'); 
console.log('2'); 
console.groupEnd(); 
console.log('6'); 
console.groupEnd(); 
```

<img>

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


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

<img>

### Tabular visualization of logs

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

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

console.table(jsonData); 
```

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616821591744/oY2AIh8p0.png?auto=compress">

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

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

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616821909570/9om9JSKgk.png?auto=compress">

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

```js
const x = { a: 1, v: { a: 1 } }; 
```

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616821970521/Pxa8ZBp2B.png?auto=compress">

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: 

```js
const x = [
    { p: 123, i: 1 }, 
    {
        p: 124, 
        i: 2, 
        x: {
            a: 1, 
            b: { s: 23 }
        }
    }
];
```

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616822319169/2JnZByG6J.png?auto=compress">

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

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

console.table(y); 
```

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1616822372891/8PQRsIs3n.png?auto=compress">

---

⚡Thanks For Reading | Happy Coding🚀