Learn how to customize the console.log function of the console in javascript, change the style of your messages and make your library more cool.

Google chrome and Mozilla Firefox allows you to customize the messages providen in the console with the console.log method. But for what can this be useful ? Well, I can not give you a right answer, but i think you'll use to make your debug messages look cooler.

Customization

To customize with css we will use the %c[characters] identifier to enable this feature in the string of the first parameter, the second parameter will be the css string that will be applied to the message, for example :

console.log('%cThe library says : you rocks !', 'background: #005454; color: #BFF8F8');

The previous code should ouput something like : 

CSS Console.log

You can even combine and customize with css different strings within only 1 message, the identifier %c helps the console to differentiate an string from another :

%cThis is the first block and %cHere begins the second block and %cHere the third

All the string needs to be encapsulated in the first parameter of the console.log function, then the others parameters respectively with a css string, for example:

console.log("%cString1 "+"%cString2","color:blue;","color:orange;");

The previous code should ouput something like :

Customize 2

Older versions of Chrome

In Google Chrome & Firefox ( older versions -32) this feature is not available, however there are the default console features whose comes already customized :

console.info("Important information"); // displays a blue circle with an i before the string
console.warn("Warning, don't do that"); // displays a white triangle (warning symbol) with an exclamation character

And should look like :

Default console warning and info

Achieve something more awesome

Although use simply css to customize a log message is pretty impressive, there is something more impressive than that ! Customize your logs with Markup, However this feature is achieved with a library.

The library is Log and you can see a working demo here. Then you'll be able to insert markup (read more about markup here) as first parameter of the log function :

log('this is *italic string*'); // output italic string with italic style
log('this is [c="color: red"]red[c] and this is [c="color: blue"]blue[c]');

Log


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors