Skip to content

Instantly share code, notes, and snippets.

@mlrawlings
Last active August 2, 2017 23:25
Show Gist options
  • Save mlrawlings/6c62c4265bada9f858f12c4714e09cf1 to your computer and use it in GitHub Desktop.
Save mlrawlings/6c62c4265bada9f858f12c4714e09cf1 to your computer and use it in GitHub Desktop.
Hide Logs
if (process.env.LOG_ONLY) {
var chalk = require('chalk');
var MOVE_LEFT = new Buffer('1b5b3130303044', 'hex').toString();
var CLEAR_LINE = new Buffer('1b5b304b', 'hex').toString();
var hiddenCount = 0;
Object.keys(console).forEach(methodName => {
var method = console[methodName];
if (method != console.Console) {
console[methodName] = function() {
var file = getCallLocation().file;
var modulePath = getModulePath(file)
if (shouldLog(modulePath)) {
if (hiddenCount) {
process.stdout.write('\n');
hiddenCount = 0;
}
method.apply(console, arguments);
} else {
process.stdout.write(MOVE_LEFT + CLEAR_LINE + chalk.gray.dim(`${++hiddenCount} hidden log${hiddenCount > 1 ? 's' : ''}`));
}
}
}
})
var minimatch = require('minimatch');
var pattern = minimatch.makeRe(process.env.LOG_ONLY);
function shouldLog(modulePath) {
return pattern.test(modulePath);
}
var path = require('path');
function getModulePath(file) {
var node_modules = '/node_modules/';
var location = file.lastIndexOf(node_modules);
if (location !== -1) {
return file.slice(location+node_modules.length);
}
return file.replace(process.cwd(), path.basename(process.cwd()));
}
function getCallLocation(depth) {
var pst, stack, file, frame;
pst = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) {
Error.prepareStackTrace = pst;
return stack;
};
stack = (new Error()).stack;
depth = !depth || isNaN(depth) ? 1 : (depth > stack.length - 2 ? stack.length - 2 : depth);
stack = stack.slice(depth + 1);
do {
frame = stack.shift();
file = frame && frame.getFileName();
} while (stack.length && file === 'module.js');
return { file };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment