Skip to content

Instantly share code, notes, and snippets.

@warriorg
Forked from jedp/gist:3166317
Created June 2, 2019 02:38
Show Gist options
  • Save warriorg/8779d29edb27a1375ff2decebe915249 to your computer and use it in GitHub Desktop.
Save warriorg/8779d29edb27a1375ff2decebe915249 to your computer and use it in GitHub Desktop.
Logging module, file, and line number of caller
var util = require('util');
const STACK_FRAME_RE = new RegExp(/at ((\S+)\s)?\(?([^:]+):(\d+):(\d+)/);
const THIS_FILE = __filename.split('/')[__filename.split('/').length - 1];
var Logger = module.exports = function Logger() {
// I like pie
};
Logger.prototype = {
/**
* Return the function name, module, line, and column of the code
* that called into this logger.
*/
_getCaller: function() {
var err = new Error();
Error.captureStackTrace(err);
// Throw away the first line of the trace
var frames = err.stack.split('\n').slice(1);
// Find the first line in the stack that doesn't name this module.
var callerInfo = null;
for (var i = 0; i < frames.length; i++) {
if (frames[i].indexOf(THIS_FILE) === -1) {
callerInfo = STACK_FRAME_RE.exec(frames[i]);
break;
}
}
if (callerInfo) {
return {
function: callerInfo[2] || null,
module: callerInfo[3] || null,
line: callerInfo[4] || null,
column: callerInfo[5] || null
};
}
return null;
},
/**
* for example ...
*/
emit: function(message) {
var caller = this._getCaller();
console.log(util.format("%s %s, line %d: %s",
caller.module, caller.function, caller.line, message));
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment