Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply colors to console.log when using multiple arguments?

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?

like image 246
Chef Tony Avatar asked Oct 16 '25 09:10

Chef Tony


1 Answers

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: enter image description here

like image 117
Артём Игнатьев Avatar answered Oct 18 '25 22:10

Артём Игнатьев