如何在 TypeScript 中获取源代码中的实际行号(用于自定义日志记录)

2024-06-19

参考文献这个问题 https://stackoverflow.com/questions/1340872/how-to-get-javascript-caller-function-line-number-how-to-get-javascript-caller我正在使用这段代码来查找自定义日志记录函数的调用者的行号:

/**
 * eLog - displays calling line number & message & dumps vars as pretty json string
 * @param {string} msg - string to display in log message
 * @param {any} dispVars - any number of variables (ellipsis , aka Rest parameters) to dump
 */
function eLog(msg:string,...dispVars:any[]){
    let caller_line = (new Error).stack.split("\n")[4];
    console.log(`eLog->Line#${caller_line}->${msg}->`);
    console.log(JSON.stringify((new Error).stack.split("\n"),null,2));
    dispVars.forEach(value => {
        console.log(JSON.stringify(value,null,2));
    });
}

像这样调用:

eLog("eLog Test",this);

虽然这确实做了正确的转储.js文件行#,我需要源行#,.ts电话号码。我怎样才能正确生成这个?


我花了一个晚上的时间完成了这个工作,并想出了一个令我满意的功能。感谢您在入门时提供的帮助 -

将其分离成log.ts

require('source-map-support').install({
	environment: 'node'
});


/**
 * eLog - displays calling line number & message & dumps vars as pretty json string
 * @param {string} msg - string to display in log message
 * @param {any} dispVars - any number of variables (ellipsis , aka Rest parameters) to dump
 * {@link https://github.com/evanw/node-source-map-support usable by typescript node-source-map-support module}
 * {@link https://github.com/mozilla/source-map/ Mozilla source-map library & project}
 * {@link http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/ good introduction to sourcemaps}
 */
export function eLog(msg:string,...dispVars:any[]){
	/**
	 * go one line back for the caller
	 * @type {string}
	 */
	let stackLine = (new Error).stack.split("\n")[2];
	/**
	 * retrieve the file basename & positional data, after the last `/` to the `)` 
	 */
	// 
	let caller_line = stackLine.slice(stackLine.lastIndexOf('/'),stackLine.lastIndexOf(')'))
	/**
	 *  test for no `/` ; if there is no `/` then use filename without a prefixed path
	 */ 
	if ( caller_line.length == 0 ) {
		caller_line = stackLine.slice(stackLine.lastIndexOf('('),stackLine.lastIndexOf(')'))
	}
	// 
	/**
	 * filename_base - parse out the file basename; remove first `/` char and go to `:`
	 */
	let filename_base = caller_line.slice(0+1,caller_line.indexOf(':'));
	/**
	 * line_no - parse out the line number ; remove first `:` char and go to 2nd `:`
	 */
	let line_no = caller_line.slice(caller_line.indexOf(':')+1,caller_line.lastIndexOf(':'));
	/**
	 * line_pos - line positional - from the last `:` to the end of the string
	 */
	let line_pos = caller_line.slice(caller_line.lastIndexOf(':')+1);
	console.log(`eLog called by ${filename_base} on line# ${line_no} @ char# ${line_pos} said:\n${msg}`);
	// print out the input variables as pretty JSON strings
	dispVars.forEach(value => {
		console.log(JSON.stringify(value,null,2));
	});
}

可以通过简单的调用:

eLog("eLog Test",this);

从任何文件只要加载该函数(例如)

import { eLog } from './log'

我希望这对其他人有帮助。

干杯,伙计们。 -埃里克

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 TypeScript 中获取源代码中的实际行号(用于自定义日志记录) 的相关文章

随机推荐