A Simple Approach To Using Console.log For Debugging

johnmeadewebdev

John Meade

Posted on January 12, 2021

A Simple Approach To Using Console.log For Debugging

Some people scoff at the console.log, some people - present company included - cherish the simple method. Here's an easy way to use it to your advantage on your front-end

A Global Constant

Key to this working well is to place a constant in the global namespace. You can pick where you want it.

window.debugCLs = true
Enter fullscreen mode Exit fullscreen mode

Now as you go about in your code you can make a decision on if there are sections where you want specific and quick console logs available to you. You may have some troublesome blocks that you just want to switch on and off as you debug, or any number of other scenarios.

try {
    ...to do this thing
} catch(e) {
    window.debugCLs && console.log(e);
}
Enter fullscreen mode Exit fullscreen mode

If you want to run a file with these logs activated, simply switch your constant to the value of true, save, and run.

Organizing Your Logs

You can organize your logs by color (or other styles) to help you quickly sort through things in the console, or to make sure your eye immediately is drawn to specific priority logs.

const modelObj = {
    value: 10,
}

try {
    const notAConst = (modelObj.value.props[0]);
} catch(e) {
    window.debugCLs && console.log('%c PRIORITY ','color:white;background-color:#044c94', e);
}
Enter fullscreen mode Exit fullscreen mode

Color-coded label for a debugging console.log

Less Is More

Obviously there is always too much of a good thing. You don't want to be sorting through a console with 500 lines of logging that are color-coded with 255 colors. That being said, four to five different categories could just help you out a bit.

And if you want to make it even more slick to handle, make your global variable an object that allows you to turn large categories on and off:

window.debugCLs = {
    apiCalls = true;
    socketNegotiations = false;
}
Enter fullscreen mode Exit fullscreen mode

Happy Coding

...and remember to always code for good :)

💖 💪 🙅 🚩
johnmeadewebdev
John Meade

Posted on January 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related