Grouping and Nesting Console Log Output

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

Organize your log output by grouping your logs into collapsable hierarchies using console.group().

It's not unusual when we are debugging something or just dumping out a bunch of log output from some process we've written to try to group like things together. For instance, this is a contrived example, but if you're like me, you've probably written code that looks something like this.

We're going to write a function that takes two arguments. We're going to say console.log, sum called, we're going to say console.log, and then put in \t, which inserts a tab. We can say the first argument was A, console.log, tab. The second argument was, we put B, and then we just return A plus B.

Then if I call sum two three, I can see that this stuff is all grouped together. Maybe you don't do that. Maybe that's just me. Something that I learned about that made my life a lot easier is something called console.group.

Let me rewrite this function that I just wrote above. Let's call this sum two, AB. We're going to say console.log, or let's just go ahead and say console.group. The sum function was called. We're going to say console.log.

Now we're not putting in tabs here. The first argument was console.log. The second argument was, and then we return A plus B. Before we do that, now we're going to type console.groupend. Now if I call sum two, two and three, I've got this nicely formatted thing.

I can even close it, and that's really cool. I can dump all sorts of stuff in here. I can, if I wanted to, I could even nest this. I could do groups inside of groups. Let's do sum three. Let's say console.group, details about the first argument.

Then we say console.groupend. We say console.group, details about the second argument. Then we group end, and then we do one more console.groupend at the end. Now if I say sum three, two and three, you can see I've got these nicely nested messages.

Mike
Mike
~ 5 years ago

Awesome. This is a great way to organize log message. Very well explained.

Victor Hazbun
Victor Hazbun
~ 4 years ago

Amazing! I didn't knew about this logging group stuff. Thanks.