This is more like a question. But, after delving ever deeper into Node.js development and looking into logging and logging frameworks like Winston, I was kind of shocked that neither provide ways to log the function name and line number of a log callsite.
There is an issue for Winston https://github.com/winstonjs/winston/issues/200 which, after having received alot of +1's, was apparently locked and their contributors are somewhat reluctant to add such essential logging capabilities into it.
Coming from Java and Java EE, I perceived logging the function name and line number as the most important thing in big-scale applications.
After reading some replies as to how people currently do it, there seems to be the way of getting the current stack trace with new Error().stack. But that gives a string representation of the stack trace elements. So, we have to decode that string again. I reckon that there existed a more structured representation of the stack before it was "stringified". So it would make sense to get hold of this structured information somehow.
Is this currently possible in Node?
Is this currently possible in Node?
Yes! :) It sounds like https://github.com/v8/v8/wiki/Stack-Trace-API#customizing-stack-traces is exactly what you are looking for.
Thanks for this awesome link! :)
However, I tried it and it does not seem to work. Can you please tell me what I am doing wrong here?
function CustomError() {
Error.captureStackTrace(this);
}
function myFunction() {
const err = new CustomError();
console.log(err.stack[0]);
console.log(err.stack[0].getFunctionName);
}
myFunction();
The output is:
E
undefined
So error.stack always seems to be in string format.
You need to override Error.prepareStackTrace to actually get the stack in a different format:
function CustomError() {
const oldStackTrace = Error.prepareStackTrace;
try {
Error.prepareStackTrace = (err, structuredStackTrace) => structuredStackTrace;
Error.captureStackTrace(this);
this.stack; // Invoke the getter for `stack`.
} finally {
Error.prepareStackTrace = oldStackTrace;
}
}
function myFunction() {
const err = new CustomError();
console.log(err.stack[0]);
console.log(err.stack[0].getFunctionName);
}
myFunction();
Wow. Very nice! Thank you! :)
I鈥檓 taking that to mean that your question has been answered, so I鈥檓 closing this, but feel free to ask follow-up questions (although this might have been better placed at https://github.com/nodejs/help).
Yes, it is resolved. I did not know about nodejs/help, though. Will ask any further questions there, then.
Most helpful comment
You need to override
Error.prepareStackTraceto actually get the stack in a different format: