Skip to content

Instantly share code, notes, and snippets.

@samrocksc
Last active April 19, 2019 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samrocksc/2b9639c99538848be7bb80f99ca63f83 to your computer and use it in GitHub Desktop.
Save samrocksc/2b9639c99538848be7bb80f99ca63f83 to your computer and use it in GitHub Desktop.
Gives the stack for name of file and line number.
const v = require('debug')('verbose');
const e = require('debug')('error');
const w = require('debug')('warning');
const buildStack = () => {
const depth = 3;
if (!this.stackIs) {
Object.defineProperty(this, 'stackIs', {
get: function() {
const orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) {
return stack;
};
const err = new Error();
Error.captureStackTrace(err, arguments.callee);
const stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
},
});
}
if (!this.lineIs) {
Object.defineProperty(this, 'lineIs', {
get: function() {
return this.stackIs[depth].getLineNumber();
},
});
}
if (!this.functionIs) {
Object.defineProperty(this, 'functionIs', {
get: function() {
return this.stackIs[depth].getFunctionName();
},
});
}
return {
function: this.functionIs,
line: this.lineIs,
};
};
/**
* base the functions to apply debugging
*/
const debug = {
verbose: msg => v(msg, buildStack()),
error: msg => e(msg, buildStack()),
warning: msg => w(msg, buildStack()),
};
function bar() {
debug.verbose('name->bar');
baz();
}
const foo = thing => {
debug.verbose('name->foo')
thing();
}
const baz = () => {
debug.verbose('name->baz');
}
foo(bar);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment