0

I'm writing a module for a logger and I want it to add a prefix each time the function dlog() is being called with the filename of the file calling the function. Right now I have to call it each time like this:

dlog(__filename + " log text");

Is there a way to detect the name of the file calling the function without this?

Tom Klino
  • 2,358
  • 5
  • 35
  • 60

1 Answers1

2

From Nodejs: get filename of caller function :

function _getCallerFile() {
    try {
        var err = new Error();
        var callerfile;
        var currentfile;

    Error.prepareStackTrace = function (err, stack) { return stack; };

    currentfile = err.stack.shift().getFileName();

    while (err.stack.length) {
        callerfile = err.stack.shift().getFileName();

        if(currentfile !== callerfile) return callerfile;
    }
} catch (err) {}
return undefined;

}

christophetd
  • 3,834
  • 20
  • 33