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!')
})()
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!')
})()
Use console.warn()
for warning logs
(() => {
// do stuff
console.warn('Warning! Something doesnt seem right.')
})()
[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)
Add your custom styles
(() => {
// do stuff
console.log('%c%s',
'color: green; background: yellow; font-size: 24px;','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')
Here's the pen.
Hope you found this useful and happy debugging! 😊