Log Js File Name And Function Name
I would like my node.js project to generate log files that are a bit similar to log4j format in that I would like each log line to commence with the file name and the js function n
Solution 1:
Edit adding all stuff.
This is a basic example of filename, lines, columns and caller function. Maybe you need to adapt somethings. But this is the idea.
let log = {
info: functioninfo(message) {
const callerInfo = getFileName(info.caller.name);
console.log(
newDate() +
' ' +
arguments.callee.name.toUpperCase() +
' ' +
callerInfo.filename +
':' +
callerInfo.line +
':' +
callerInfo.column +
' ' +
info.caller.name +
'() ' +
message
);
},
};
functiongetFileName(caller) {
constSTACK_FUNC_NAME = newRegExp(/at\s+((\S+)\s)?\((\S+):(\d+):(\d+)\)/);
let err = newError();
Error.captureStackTrace(err);
let stacks = err.stack.split('\n').slice(1);
let callerInfo = null;
for (let i = 0; i < stacks.length; i++) {
callerInfo = STACK_FUNC_NAME.exec(stacks[i]);
if (callerInfo[2] === caller) {
return {
filename: callerInfo[3],
line: callerInfo[4],
column: callerInfo[5],
};
}
}
returnnull;
}
functioniWantToLog() {
log.info('Testing my log');
}
iWantToLog();
Solution 2:
A colleague suggested using a Gulp PreProcess to solve this issue. The idea being I would not perform any of the manual steps 1) 2) and 3) described above, however before running/deploying my code, I would feed it through a Gulp preprocess which would update all my js source code, adding all of code described in steps 1) 2) and 3).
I have not used Gulp much, but on the surface, this sounds like a promising idea. On the upside:
- as long as Gulp can update my source files as required it will work
- should not cause any significant runtime js performance issues, no requirement for generation of js Error objects to create stack traces from which to extract script and function names
- my source code will not be littered with any of this extra code to log script name and function name
On the down side:
- need to make Gulp part of my workflow - that seems acceptable
- I need to setup the gulp preprocessor to alter my js source - no idea how hard this will be, would gulp pre-process be my starting point?
- when I make code changes to js source files Gulp will need to rerun each time, impacting my iteration time
Post a Comment for "Log Js File Name And Function Name"