45

Is there a way to do something like:

console.log("hello world", '#FF0000')

in Chrome/Safari or Firefox ?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Blacksad
  • 14,906
  • 15
  • 70
  • 81
  • Same question here http://stackoverflow.com/questions/7505623/colors-in-javascript-console – David Xia Feb 17 '12 at 17:51
  • 4
    No, that's not the same question. Please remove your close request. In the question you referenced, the guy wants to change the color for ALL log messages. I would like to change it on a per message basis. – Blacksad Feb 17 '12 at 20:13
  • Ah, sorry. I'm not sure how to remove my close request. I don't see anything to do that. – David Xia Feb 17 '12 at 20:15

6 Answers6

62

You can use the following:

function colorTrace(msg, color) {
    console.log("%c" + msg, "color:" + color + ";font-weight:bold;");
}
colorTrace("Test Me", "red");
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Shane
  • 4,921
  • 5
  • 37
  • 53
  • this will give wrong line number in the output - it will show the line where actual native `console.log` invoked – godblessstrawberry Sep 23 '17 at 09:12
  • @godblessstrawberry - correct, just replace the variable in the function with console.log("%c my message", "color:#993333;font-weight:bold;");, I put the function in for convenience as the original question didn't specify what was preferred so I optimized for re-use. – Shane Sep 28 '18 at 01:36
  • @Shane what are you talking about? I'm saying this function solution is useless in terms of debugging as it always will point to the wrong line where `console.log()` was invoked not where `colorTrace()` was called – godblessstrawberry Oct 03 '18 at 11:08
34

Made this and its been helpful:

function log(msg, color) {
    color = color || "black";
    bgc = "White";
    switch (color) {
        case "success":  color = "Green";      bgc = "LimeGreen";       break;
        case "info":     color = "DodgerBlue"; bgc = "Turquoise";       break;
        case "error":    color = "Red";        bgc = "Black";           break;
        case "start":    color = "OliveDrab";  bgc = "PaleGreen";       break;
        case "warning":  color = "Tomato";     bgc = "Black";           break;
        case "end":      color = "Orchid";     bgc = "MediumVioletRed"; break;
        default: color = color;
    }

    if (typeof msg == "object") {
        console.log(msg);
    } else if (typeof color == "object") {
        console.log("%c" + msg, "color: PowderBlue;font-weight:bold; background-color: RoyalBlue;");
        console.log(color);
    } else {
        console.log("%c" + msg, "color:" + color + ";font-weight:bold; background-color: " + bgc + ";");
    }
}

Use:

log("hey"); // Will be black
log("Hows life?", "green"); // Will be green
log("I did it", "success"); // Styled so as to show how great of a success it was!
log("FAIL!!", "error"); // Red on black!
var someObject = {prop1: "a", prop2: "b", prop3: "c"};
log(someObject); // prints out object
log("someObject", someObject); // prints out "someObect" in blue followed by the someObject
NightOwlPrgmr
  • 1,322
  • 3
  • 21
  • 31
Jaden Travnik
  • 1,107
  • 13
  • 27
9

ALL of currently given answers will cause major debugging issue - the line number reported in the log output will always correspond to the line where the custom log function ultimately invokes the native console.log

Simple coloring is available in the regular console.log - just prepend first parameter with %c and pass stringified css rules as a second parameter:

console.log(`%c[stackoverflow] postAnswer()`, ';background: lightblue; color: #444; padding: 3px; border-radius: 5px;');

This is how it looks in the console: enter image description here

Proper logging wrapper you could find under this answer

A proper wrapper for console.log with correct line number?

For VSCode users:

Here's keybindings snippet that wraps your clipboard into nice log and allows you to choose the color:

{
    "key": "cmd+alt+l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
        "snippet": "console.log(`%c[${WORKSPACE_NAME/(.*)/${1:/upcase}/}] ${CLIPBOARD}`, '${2|;background: lightblue; color: #444;,;background: lightgreen; color: #444;,;background: lightsalmon; color: #444;,;background: lightcyan; color: #444;,;background: lightpink; color: #444;,;background: lightseagreen; color: #444;,;background: lightskyblue; color: #444;,;background: lightsteelblue; color: #444;,;background: khaki; color: #444;,;background: purple; color: white;,;background: salmon; color: white;,;background: blue; color: white;,;background: #444; color: white;,;background: green; color: white;,‍♀️;background: blueviolet; color: white;,;background: chocolate; color: white;,‍;background: mediumvioletred; color: white;,;background: brown; color: white;,;background: cadetblue; color: white;,;background: cornflowerblue; color: white;,;background: crimson; color: white;,;background: red; color: white;|} padding: 3px; border-radius: 5px;');"
    }
}

just add this entry into your keybindings.json - on mac its here: ~/Library/Application Support/Code/User/keybindings.json

This is how it looks in VSCode:

enter image description here

godblessstrawberry
  • 4,556
  • 2
  • 40
  • 58
  • Which wrapper will accept the necessary second argument for colorization? There are a lot of answers and most rely directly on bind, which doesn't let you bind trailing arguments. – John Neuhaus Nov 21 '17 at 17:22
  • I don't use wrappers, I use my vscode snippet which is enough for my debugging purposes – godblessstrawberry Aug 04 '21 at 19:17
2

You with the following snippet you can use the console.log command as you wished!

  • Chrome ✔️
  • Firefox ✔️
  • Safari ✔️

(function () {
    $consoleLog = console.log;
  console.log = function ($message, $color) {
    $consoleLog('%c' + $message, 'color:' + $color + ';font-weight:bold;');
  }
})();

console.log('test', 'green');

OR

https://jsfiddle.net/mL88u3n9/

howtoweb
  • 349
  • 1
  • 3
  • 10
2

You can add functions to the object console, for example I use this function for success

console.success = (message) => { 
  console.log('%c ' + message, 'color: green; font-weight:bold') 
}

console.success('I am a successfull message')

enter image description here

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
1

Inspired by Jaden's answer. Made a little log function.

function log(msg, color) {

  var css = "",
  paint = { // default colors
    clr: "#212121",
    bgc: "#b0bec5"
  },
  colors = {
    error: {clr:"#ffebee", bgc:"#c62828"}, // red
    success: {clr: "#e8f5e9", bgc: "#2e7d32"}, // green
    warning: {clr: "#fff3e0", bgc: "#f4511e"}, // orange
    info: {clr: "#ede7f6", bgc: "#651fff"} // purple
  };

  // overriting default colors if color given
  if (colors.hasOwnProperty(color)){ paint.clr = colors[color].clr; paint.bgc = colors[color].bgc; }
  css = "color:" + paint.clr + ";font-weight:bold; background-color: " + paint.bgc + "; padding: 3px 6px; border-radius: 2px;";

  console.log("%c"+msg, css);
}

Test

log("Default");
log("Error", "error");
log("Success", "success");
log("Warning", "warning");
log("Info", "info");

What it looks like

Väsä
  • 31
  • 4