Better console.logs

October 18, 2018

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!')
})()

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!')
})()

errorlog

Use console.warn() for warning logs

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

warninglog

Use console.table() for iterable objects

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

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

console.table(me)

tablelog

Add your custom styles

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

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')

custom_function

Here's the pen.

Hope you found this useful and happy debugging! ๐Ÿ˜Š



ad free site