Log caller function name and line number
See original GitHub issueThere does not seem to be a way to log the caller’s method name and line number. I know that this has already been requested with #200, but that issue was locked with the reason that such a function would be very slow. Given that a typical application would not excessively log thousands of log statements per second, it does not make a noticeably difference.
As you probably know, JavaScript provides the stack trace in the Error.stack
property on construction of a new Error object. However, this is an unstructured string and needs to be parsed.
V8 on the other hand has a feature allowing to retrieve the stack trace in its original structured form (before stringifying). This is described here: https://github.com/v8/v8/wiki/Stack-Trace-API
My current implementation on top of Winston looks like this. (It may not be a good implementation, I’m very new to JavaScript and Node/V8. 😃 )
// ES2015
const path = require('path');
const winston = require('winston');
function CustomError() {
// Use V8's feature to get a structured stack trace
const oldStackTrace = Error.prepareStackTrace;
const oldLimit = Error.stackTraceLimit;
try {
Error.stackTraceLimit = 3; // <- we only need the top 3
Error.prepareStackTrace = (err, structuredStackTrace) => structuredStackTrace;
Error.captureStackTrace(this, CustomError);
this.stack; // <- invoke the getter for 'stack'
} finally {
Error.stackTraceLimit = oldLimit;
Error.prepareStackTrace = oldStackTrace;
}
}
function getAndFormatStackTraceElement() {
const stack = new CustomError().stack;
const CALLER_INDEX = 2; // <- position in stacktrace to find deepest caller
const element = stack[CALLER_INDEX];
const fileName = path.basename(element.getFileName());
return element.getFunctionName() + "(" + fileName + ":" + element.getLineNumber() + ")";
}
module.exports = {
info(msg, ...vars) {
winston.info(getAndFormatStackTraceElement() + ': ' + msg, ...vars);
}
}
Credits go to @addaleax from: https://github.com/nodejs/node/issues/7749#issuecomment-232972234 The way the string is formatted and the module exports are defined, sure needs reworking, I guess.
This ticket could serve as a discussion on how a good PR would look like for Winston, adding this feature to the library.
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (1 by maintainers)
Top GitHub Comments
please provide a option to enable this feature, like log4js
Thanks for the suggestion @httpdigest! But as you said this is a duplicate of #200, so going to close it. Will leave the issue unlocked to keep the discussion going this time.