✒️
Start your developer blog today!
✉️
Questions?
Email me

How to console.log with Colors in JavaScript

May 12, 2020 2 min read

I’m sure we’re all familiar with console.log() in JavaScript, since it’s the main debugging tool for many developers. But how can we improve our logs with some colors in the console?

Perhaps we’ve also learned about the following:

  • console.info() for informational messages
  • console.error() for errors
  • console.warn() for warnings
  • console.table() for iterable objects

Let’s take this a step further and find how we can apply custom styles to our logs.

The %c Flag

We can apply our own styling to a log message by doing two things:

  • Prefixing the message with the %c flag
  • Providing a string of CSS as the second parameter

As a simple example, we can make the log message orange.

console.log("%cLog Message", "color: orange");

The string of CSS can get pretty long, so I recommend defining the styles separately in an array and joining each element with a semi-colon.

It’s reusable and much cleaner than manually type out the CSS string.

Pro Tip: it’s all about the padding and border-radius.

let baseStyles = [
    "color: #fff",
    "background-color: #444",
    "padding: 2px 4px",
    "border-radius: 2px"
].join(';');
console.log("%cLog Message", baseStyles);

I encourage you to try this out in your console right now, and check out what’s possible.

A Step Further

We can take this a step further and create our own set of logging methods.

This also allows us to avoid typing out the %c flag for every log message.

function log(msg, type) {
    // Define different types of styles
    let baseStyles = [
        "color: #fff",
        "background-color: #444",
        "padding: 2px 4px",
        "border-radius: 2px"
    ].join(';');
    let ajaxStyles = [
        "color: #eee",
        "background-color: red"
    ].join(';');
    let domStyles = [
        "background-color: gray"
    ].join(';');
    let successStyles = [
        "background-color: green"
    ].join(';');
    // Set style based on input type
    let style = baseStyles + ';';
    switch(type) {
        case "ajax": style += ajaxStyles; break;
        case "dom": style += domStyles; break;
        case "success": style += successStyles; break;
        default: break;
    }
    console.log(`%c${msg}`, style);
}
log("Normal Logs");
log("AJAX Logs", "ajax");
log("DOM Logs", "dom");
log("Success Logs", "success");

More JavaScript Articles