Wednesday, November 14, 2018

Colorful Console Message In Javascript

This tutorial explains how to display colorful console message in javascript. Especially if you have a huge application where there are tons of logs being printed out in the browser console. Styling your log message will make sure those important messages get displayed and don't get buried.

Colorful Console Message In Javascript

Lets see the below example to create colorful console message in browser console. Whenever you want to print color console message in browser console, then apply the below line of code in your javascript.

// place this in your browser console
console.log('%cHello', 'color: green; background: yellow; font-size: 30px');

I think now you have a question what is %c present inside the console.log block. %c: Applies CSS style rules to the output string as specified by the second parameter

Output in browser console :

Colorful Console Message In Javascript

Apply Multiple Console Message Styles

To add multiple style, you just pre-pend the message with %c. The text before the directive will not be affected. Only the text after the directive will be styled using the CSS declarations in the parameter.
  'Nothing here %cHi Cat %cHey Bear',  // Console Message
  'color: blue', 'color: red' // CSS Style

Output :
Colorful Console Message In Javascript

Also you can apply the below 5 types of console messages:
  1. console.log
  3. console.debug
  4. console.warn
  5. console.error
Lets check the below example for more information.
console.log('%cconsole.log', 'color: green;');'', 'color: green;');
console.debug('%cconsole.debug', 'color: green;');
console.warn('%cconsole.warn', 'color: green;');
console.error('%cconsole.error', 'color: green;');

Passing the console CSS style as an Array

You can pass the styles as an array. And then you can use the join() method to turn the array style elements into a string.
// 1. Pass the css styles in an array
const styles = [
  'color: green', 
  'background: yellow', 
  'font-size: 30px',
  'border: 1px solid red',
  'text-shadow: 2px 2px black',
  'padding: 10px',
 // 2. Concatenate the individual array item and concatenate them into a string separated by a semi-colon (;)

// 3. Pass the styles variable
console.log('%cHello There', styles);

Refactoring console message with %s

Beside cleaning up the console message by passing the styles as an array. We can also clean up the message using the %s specifier.
const styles = ['color: green', 'background: yellow'].join(';');

const message = 'Some Important Message Here';

// 3. Using the styles and message variable
console.log('%c%s', styles, message);

This is all about Colorful Console Message In Javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment