DEV Community

Cover image for Better console.logs
Kelvin Wangonya
Kelvin Wangonya

Posted on

Better console.logs

If you work with javascript a lot, you probably often need to use console.log() to output some info as you go along.

It's usually just the plain old way though:

(() => {
    // do stuff
    console.log('Success!')
})()
Enter fullscreen mode Exit fullscreen mode

plain

Here are a few ways you could make your logs a bit more visually informative, and interesting πŸ™‚

Use console.error() for error logs

(() => {
    // do stuff
    console.error('Oops, something went wrong!')
})()
Enter fullscreen mode Exit fullscreen mode

errorlog

Use console.warn() for warning logs

(() => {
    // do stuff
    console.warn('Warning! Something doesnt seem right.')
})()
Enter fullscreen mode Exit fullscreen mode

warninglog

[Edit] Use console.table() for iterable objects

Thanks to @shoupn and @squgeim for pointing this out in the comments :)

function Person(firstName, lastName) {
  this.firstName = firstName
  this.lastName = lastName
}

const me = new Person('John', 'Smith')

console.table(me)
Enter fullscreen mode Exit fullscreen mode

tablelog

Add your custom styles

(() => {
    // do stuff
    console.log('%c%s',
            'color: green; background: yellow; font-size: 24px;','Success!')
})()
Enter fullscreen mode Exit fullscreen mode

custom_success

You can have a custom function in your code that lets you use "your own" log with colors directly

function customLog(message, color='black') {
     switch (color) {
         case 'success':  
              color = 'Green'
              break
         case 'info':     
                 color = 'Blue'  
              break;
         case 'error':   
              color = 'Red'   
              break;
         case 'warning':  
              color = 'Orange' 
              break;
         default: 
              color = color
     }

     console.log(`%c${message}`, `color:${color}`)
}

customLog('Hello World!')
customLog('Success!', 'success')
customLog('Error!', 'error')
customLog('Warning!', 'warning')
customLog('Info...', 'info')
Enter fullscreen mode Exit fullscreen mode

custom_function

Here's the pen.

Hope you found this useful and happy debugging! 😊

Latest comments (42)

Collapse
 
nightdvlpr_50 profile image
Amir

It was useful. Good job.
I've published a tiny package about this topic.
npmjs.com/package/havecoolconsole

Collapse
 
yaireo profile image
Yair Even Or • Edited

I've authored "console colors", a tiny package which allows easy fun coloring:

github.com/yairEO/console-colors

Collapse
 
alexr89 profile image
Alex

Is it possible to console.log within a width, so for example the entire width of the console?

Collapse
 
nightdvlpr_50 profile image
Amir

Absolutely yes.
Just set display: block; & width: 100vw;

console.log('%c%s', 'display:block;width:100vw;background-color:#cff1de;color:green;font-size:25px','Hello Console!');

Collapse
 
julesmanson profile image
jules manson • Edited

As a temporary measure for writing quicker console.log()'s just put the following in a temporary file (for polluting the global namespace) and link it to the top of your web application then unlink it when no longer needed:

const log = (...args) => console.log(...args);

Now you can easily do...

log(message, ' : ', func.name, func(arg));

Error at nameOfFunc : undefined // example output

This is especially useful when logging multiple test cases in a single run. Similarly can be done with the other console methods. And if you really want to go crazy, this can also be done with Object.prototype.methods but you must often bind the function to the calling object's scope by setting the context with Function.prototype.bind or Function.prototype.call. I think ES5 and ES6 have made Function.prototype.apply obsolete so I don't use it or recommend it anymore. But only do this on very small projects or inside created objects.

Collapse
 
enriquemorenotent profile image
Enrique Moreno Tent

Do not forget "console.group"!

enriquemorenotent.com/post/differe...

Collapse
 
jmscavaleiro profile image
jmscavaleiro

Short, simple and easy! Thanks!

Collapse
 
gypsydave5 profile image
David Wickes

That's great - I didn't know about console.table. That's some very cool web-fu.

BUT!

Remember - all this debugging is as nothing to the power of good automated tests. A debug line should be ephemeral - an automated test is for life!

Collapse
 
shubhambattoo profile image
Shubham Battoo

@itsmanojb something we were talking about the other day, what was that video you shared?

Collapse
 
itsmanojb profile image
Manoj Barman

That was from Angular firebase. Here the full video youtu.be/Mus_vwhTCq0

Collapse
 
robustdj profile image
Derrick Camerino

Cool! Didn't know about the styling/coloring

Collapse
 
wangonya profile image
Kelvin Wangonya

Glad you learnt something :)

Collapse
 
aghost7 profile image
Jonathan Boudreau

I'm a big fan of the debug module. For debug logs that you don't remove afterwards it is very nice.

Another nice thing is console.trace, which also prints out a stack trace where the log is called. Useful if you're trying to debug a function which is being called in several critical areas.

Collapse
 
nblackburn profile image
Nathaniel Blackburn • Edited

I have gone about this via namespacing my debug logs so it assigns a colour based on that namespace.

debug('cache:set', {}) // cache:set +1ms {}

The namespace here being cache which is mapped against an array of colours using the following code...

let log = 'cache:set';
let colors = [];

const hash = data => {
    let hash = 0;

    for (let index = 0; index < data.length; index++) {
        hash = ((hash << 5) + hash + data.charCodeAt(index)) & 0xffffffff;
    }

    return hash;
};

let namespace = log.substring(0, log.indexOf(':'));
let color = colors[Math.abs(hash(namespace)) % colors.length];

This way cache logs are always shown in the same colour allowing you to visually identify them.

Collapse
 
nssimeonov profile image
Templar++

Idea: Make this an npm package. Wait for it to become popular enough. Inject code to steal credit cards :)

(There was an article about this a few months ago, luckily it was a joke)

Collapse
 
lmbarr profile image
Luis Miguel • Edited

I use console.trace to check the stack calls. I use also console.log({variableName}) to get the variableName in the console..

Collapse
 
sreubenstone profile image
sreubenstone

dope

Collapse
 
wangonya profile image
Kelvin Wangonya

Glad you liked it @sreubenstone

Collapse
 
thomasbnt profile image
Thomas Bnt β˜•

Nice for adding colors on console. It's better!

Collapse
 
wangonya profile image
Kelvin Wangonya

Yeah! Hope you'll try it out on your next project :)

Collapse
 
thomasbnt profile image
Thomas Bnt β˜•

It's already done ! I've seen this before, but your article complements this feature.