DEV Community

Code Craft-Fun with Javascript
Code Craft-Fun with Javascript

Posted on • Originally published at code-craft.hashnode.dev on

Start using console logs in this way!🏳️‍🌈

Style console logs!

We use console logs mostly while debugging our application. Sometimes we use it for giving some warnings, or information or displaying some errors to users. What if I say that you can style these logs in whatever way you want? Yes, this is possible. This can be handy when you are working on a huge application with loads of logs printed on the console. Styling these important logs will make sure it doesn't get lost in those number of logs. We will be seeing how we can do this. Also, I will share some tips and tricks to easily manage the styles for your logs.


%c specifier

%c gives you the power to style your logs. let's see how it works with some examples.

// Try to run this directly in the browser console and check the magic!
console.log('%cMy Log', 'color: red; background: wheat; font-size: 30px');

Enter fullscreen mode Exit fullscreen mode

What did you see after running this code in your browser's console? Yes! 😁

example

You got the power now !

%c : Applies CSS style rules to the output string as specified before the log string.


Use multiple %c in a single console log

console.log(
  'Multiple styles for %cHi John %cHey Alice', // Console Message
  'color: blue', // CSS Style for Hi John
  'color: red', // CSS Style for Hey Alice
);

Enter fullscreen mode Exit fullscreen mode

example

%c can be used in all available types of console logs ie, console.info, console.debug, console.warn, console.error. It can be used in the same way in all types of logs.


Tips for clean code

  • Separate the complex CSS styles in a variable.
    const styles = ['color: green', 'background: yellow'].join(';');

    const message = 'My Logs';

    // 3. Using the styles and message variable
    console.log('%c%s', styles, message);
    // here %c is used for style as we all know, and %s will be replaced with the string stored in message variable ie; "My Logs"

Enter fullscreen mode Exit fullscreen mode

Hope you have learnt something new today. If you find this useful share this knowledge with other passionate developers like you. Happy Reading. 🌈

Top comments (0)