Better console.logs

Kelvin Wangonya - Oct 18 '18 - - Dev Community

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! 😊

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player