如何创建一个在右侧显示文件名和行号的日志系统。
例如,当我跑步
console.log('Hello world');
在“ index.js”中将记录
"Hello world (index.js:1)"
您可以使用错误的堆栈跟踪来获取文件和行号:
function getFileLine(callee) {
const orig = Error.prepareStackTrace;
Error.prepareStackTrace = (err, stack) => [stack[0].getFileName(), stack[0].getLineNumber()];
const err = new Error();
Error.captureStackTrace(err, callee);
const lineNum = err.stack;
Error.prepareStackTrace = orig;
return lineNum;
}
function logger(...args) {
console.log(...args, `(${getFileLine(logger).join(":")})`);
}
logger("foobar");
如果提供的文件名太长,无法满足您的需求,则可以使用path.basename
:
const path = require("path");
function getFileLine(callee) {
const orig = Error.prepareStackTrace;
// there's a basename call here
Error.prepareStackTrace = (err, stack) => [path.basename(stack[0].getFileName()), stack[0].getLineNumber()];
const err = new Error();
Error.captureStackTrace(err, callee);
const lineNum = err.stack;
Error.prepareStackTrace = orig;
return lineNum;
}
function logger(...args) {
console.log(...args, `(${getFileLine(logger).join(":")})`);
}
logger("foobar");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句