I’m working on a JavaScript project and I want to make my console output more visually organized. Right now all my console messages look the same and it’s hard to quickly spot different types of information.
Is there a way to make different console messages appear in different colors? For example, I’d love to have my error messages show up in red text, warning messages in yellow or orange, and regular debug messages in green.
I’m using Chrome for development but I’m wondering if this works in other browsers too. Here’s a simple example of what I’m trying to colorize:
function displayMessage(type, text) {
if (type === 'error') {
console.error(text); // want this red
} else if (type === 'warning') {
console.warn(text); // want this orange
} else {
console.log(text); // want this green
}
}
displayMessage('error', 'Something went wrong!');
displayMessage('warning', 'This might be an issue');
displayMessage('info', 'Everything is working fine');
Any suggestions on how to achieve this colored console output?
No need to remember CSS syntax every time, and you can tweak all the styling from one spot. The background colors and padding really make messages pop. Works great in Chrome, Firefox and Edge. You could add timestamps or more log levels if you want.
You can get colored console output using CSS styling with the %c format specifier. Works great in Chrome, Firefox, and most modern browsers. Here’s how to modify your function:
The %c tells the console to apply CSS styles from the second parameter to your text. You can mix in background colors, padding, borders - whatever you want. I’ve used this for debugging complex apps and it makes spotting different message types way faster. Just remember that console.error() and console.warn() already have default styling, but the %c approach gives you complete control over how things look.