Console Log Output – Substitution and CSS in Chrome

Debugging should be more colorful.

Console.log in Chrome accepts a number of parameters including css.

Output can be stylized by using %c prior to the stylized text.

Example:

console.log("I'm%c Colorful.", "color: blue; font-size:14px");

A simple utility wrapper I use to stylize console.log output.

var styled = (function () {

var fontStyle = 'font-family: Helvetica,Arial,sans-serif; font-size: 13px;', boxStyle = ' line-height: 25px; padding: 5px 5px; border-radius: 4px;', styles = { msg : ' color: #eee; background: #222; ' + fontStyle + boxStyle, err : ' color: #0F0; background: #222; ' + fontStyle + boxStyle }, log = function (msg, styleStr) { if (styleStr) { console.log('%c' + msg, styles[styleStr]); } else { console.log('%c' + msg, styles.msg); } } return log; }());

styled('New Log Style. '); 
styled('New Error Style. ', 'err');

Additional Console substitutions.

As String:

console.log('%s', 'String'); // String

As Integer:

console.log('%d', 5.3); // 5
console.log('%i', 5.3); // 5

As Float:

console.log('%f', 5.3); // 5.3

Displaying expandable Objects / Arrays (note: css cannot style this output).

console.log('Expandable object or array %O', {type:'color', color:'blue'}); // Expandable object or array Object

Random Example:

console.log("I'm%c - %c%s%c.", "color: black; font-size:19px", "color: blue; font-size:14px", "Colorful", "color: black; font-size:19px");

Leave a Reply

Your email address will not be published. Required fields are marked *