I'm trying to style the output of my console.log()
to make my application errors stand out.
So far this works:
console.log('%cHello World', 'background: #222; color: #bada55');
But this doesn't:
var text = "Hello World";
var style = "background: #222; color: #bada55";
console.log('%c', text, style);
It just returns background: #222; color: #bada55
. What am I missing?
When you need to log multiple arguments, you can use following approach:
const log = (...args) => {
let messageConfig = '%c%s ';
args.forEach((argument) => {
const type = typeof argument;
switch (type) {
case 'bigint':
case 'number':
case 'boolean':
messageConfig += '%d ';
break;
case 'string':
messageConfig += '%s ';
break;
case 'object':
case 'undefined':
default:
messageConfig += '%o ';
}
});
console.log(messageConfig, 'color: orange', '[LOGGER]', ...args);
};
log('my message', 123, 'qwerty', { foo: 'bar' }, [1, 2, 3, 4, 5]);
here is result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With