JS | Current File - Call Trace

by Zoltan Boros

HTML

<pre id="out"></pre>

JavaScript

const out = document.getElementById('out');

const print = (s) => {
	out.innerHTML += s + '\n';
};

const getCallTrace = () => {
	const error = new Error('fake error to get call trace');
  const trace = error.stack.split('\n').filter((item, i) => i > 0 && item.length > 0);
  return trace;
};

const traceLog = (...args) => {
	console.log('[' + getCallTrace()[0] + ']', ...args);
};

const func1 = () => {
	traceLog('Foo', 'Bar');
};

const func2 = () => {
	getCallTrace().forEach(item => print(item));
	func1();
};

const func3 = () => {
	func2();
};

func3();