Published
Edited
Apr 27, 2022
Importers
Insert cell
Insert cell
function consoleLogBlacklist(blacklist = [], functionsToPreserve = ["error"]) {
/*
* How to disable console.log for specific files
* https://stackoverflow.com/a/39648992
*/
function noop() {}

//ensure we KNOW that there is a log function here, just in case
const savedFunctions = {
log: console.log
};

//proceed with nuking the rest of the chattiness away
Object.keys(console).reduce((memo, key) => {
if (
typeof console[key] == "function" &&
functionsToPreserve.indexOf(key) != -1
) {
memo[key] = console[key];
console[key] = noop;
}

return memo;
}, savedFunctions); //<- it's a const so we can't re-assign it. Besides, we don't need to, if we use it as a seed for reduce()

console.log = function customLog() {
//index 0 - the error message
//index 1 - this function
//index 2 - the calling function, i.e., the actual one that did console.log()
const callingFile = new Error().stack.split("\n")[2];

if (blacklist.some((entry) => callingFile.includes(entry))) {
return;
} else {
savedFunctions.log.apply(console, arguments);
}
};
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more