Is there a way to do something like:
console.log(\"hello world\", \'#FF0000\')
in Chrome/Safari or Firefox ?
This works:
function colorTrace(msg, color) {
console.log("%c" + msg, "color:" + color + ";font-weight:bold;");
}
colorTrace("Test Me", "red");
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')
Simple and nice:
console.log("%cHello World", "color:#fff;background:#08c;padding:5px;border-radius:8px")
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
You with the following snippet you can use the console.log command as you wished!
(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/
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
coloring is achievable by adding %c
on the beginning of first parameter and simple css rules as a second parameter of console.log
:
console.log('%c' + $message, 'color:' + $color + ';background-color: #444; padding: 3px 7px; margin-left: -7px;');
and the proper logging wrapper you could find under this answer
A proper wrapper for console.log with correct line number?