Start Styling your console logs!๐ณ๏ธโ๐๐คฉ
You can provide custom css and style the console logs in your way
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');
What did you see after running this code in your browser's console? Yes! :grin:
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
);
%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 logStyle = [ 'color: wheat', 'background: red', 'font-size: 20px', 'border: 1px solid black', 'text-shadow: 2px 2px black', 'padding: 10px', ].join(';'); // trick to concatinate each style attribute separated by semicolon (;) console.log('%cMy Logs', logStyle); // use the variable directly
Use dynamic log strings. Refactor log string using
%s
specifier.As simple as that!
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"
Hope you have learnt something new today. If you find this useful share this knowledge with other passionate developers like you. Happy Reading. ๐