jam*_*ack 60 javascript google-chrome v8 node.js
花在C之类的语言上的JavaScript开发人员经常会错过使用某些类型的内省的能力,比如记录行号,以及调用当前方法的方法.好吧,如果您使用的是V8(Chrome,Node.js),您可以使用以下内容.
jam*_*ack 93
Object.defineProperty(global, '__stack', {
get: function(){
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack){ return stack; };
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
}
});
Object.defineProperty(global, '__line', {
get: function(){
return __stack[1].getLineNumber();
}
});
console.log(__line);
Run Code Online (Sandbox Code Playgroud)
以上将记录19.
结合arguments.callee.caller您可以更接近通过宏在C中获得的有用日志记录的类型.
接受的答案 IMO 的问题在于,当您想打印某些内容时,您可能会使用记录器,在这种情况下,使用已接受的解决方案将始终打印同一行:)
一些小的改变将有助于避免这种情况!
在我们的例子中,我们使用 Winston 进行日志记录,因此代码如下所示(注意下面的代码注释):
/**
* Use CallSite to extract filename and number, for more info read: https://v8.dev/docs/stack-trace-api#customizing-stack-traces
* @returns {string} filename and line number separated by a colon
*/
const getFileNameAndLineNumber = () => {
const oldStackTrace = Error.prepareStackTrace;
try {
// eslint-disable-next-line handle-callback-err
Error.prepareStackTrace = (err, structuredStackTrace) => structuredStackTrace;
Error.captureStackTrace(this);
// in this example I needed to "peel" the first CallSites in order to get to the caller we're looking for
// in your code, the number of stacks depends on the levels of abstractions you're using
// in my code I'm stripping frames that come from logger module and winston (node_module)
const callSite = this.stack.find(line => line.getFileName().indexOf('/logger/') < 0 && line.getFileName().indexOf('/node_modules/') < 0);
return callSite.getFileName() + ':' + callSite.getLineNumber();
} finally {
Error.prepareStackTrace = oldStackTrace;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25226 次 |
| 最近记录: |