Skip to content

Instantly share code, notes, and snippets.

@fliptopbox
Last active June 28, 2019 10:26
Show Gist options
  • Save fliptopbox/f6dbd1dc1184606421f3f516f226d2fa to your computer and use it in GitHub Desktop.
Save fliptopbox/f6dbd1dc1184606421f3f516f226d2fa to your computer and use it in GitHub Desktop.
Creates a window method that returns an Array of arguments to colour code the console.log output. Each log has a timestamp, and time diff of the last log, the log message is uniquely coloured according to the 1st string in the argument list
/*
Console log index by color
Creates a window method that returns an Array of
arguments to colour code the console.log output
Each log has a timestamp, and time diff of the last log,
the log message is uniquely coloured according
to the 1st string in the argument list
Usage:
console.log.apply(console, _c("Log identifier", optional, values));
*/
(function() {
let ts = 0;
const ns = "c";
const unique = {};
function rgba(opacity = 0.4) {
// returns String
//
// Generates an Array of random rgb colours,
// formatted CSS value eg. "rgb(123, 23, 111, 0.4)"
const array = [...Array(4)].map((_, n) => n > 2 ? opacity : (Math.random() * 255) >> 0);
return `rgba(${array.join(",")})`;
}
function getConsoleArguments() {
const time = (performance.now() >> 0) / 1000;
const diff = ((Math.max(0, time - ts) * 100) >> 0) / 100;
const args = arguments && arguments.length ? [...arguments] : ["LOG"];
const id = args.splice(0, 1)[0];
const color = unique[id] || (unique[id] = rgba());
const array = [
`%c[%s] %s`,
`background: ${color}; padding: 2px;`,
`${time >> 0}s (${diff})`,
id,
...args
];
ts = time;
return array;
}
window[ns] = getConsoleArguments;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment