JS 堆栈&内存快照& tracre跟踪

堆栈跟踪 API

V8 中抛出的所有内部错误在创建时都会捕获堆栈跟踪。可以通过非标准error.stack属性从 JavaScript 访问此堆栈跟踪。V8 还具有各种钩子,用于控制堆栈跟踪的收集和格式化方式,以及允许自定义错误也收集堆栈跟踪。本文档概述了 V8 的 JavaScript 堆栈跟踪 API。


function getStack(error) {
  const orig = Error.prepareStackTrace;
  Error.prepareStackTrace = (_, stack) => stack;
  const stack = error.stack;
  Error.prepareStackTrace = orig;
  return stack;
}

function trace() {
  try {
    throw new Error('stack');
  }
  catch (error) {
    console.log(getStack(error)[0].getFunctionName());
  }
}

function b() {
  trace();
}

function a() {
  b();
}

a()


// 参考文档:堆栈跟踪 API:(https://v8.dev/docs/stack-trace-api)

tracre 记录

const { Session } = require('inspector');
const session = new Session();
session.connect();
function post(message, data) {
  return new Promise((resolve, reject) => {
    session.post(message, data, (err, result) => {
      if (err)
        reject(new Error(JSON.stringify(err)));
      else
        resolve(result);
    });
  });
}

async function test() {
	session.on('NodeTracing.dataCollected', (data) => {
	  console.log(data.params.value);
	});
	
	session.on('NodeTracing.tracingComplete', () => {
		console.log('done');
	});
	const { categories } = await post('NodeTracing.getCategories');
	const traceConfig = { includedCategories: categories };
	await post('NodeTracing.start', { traceConfig });
	setTimeout(() => {
		post('NodeTracing.stop');
	}, 1000);
}

test();

参考:https://blog.csdn.net/THEANARKH/article/details/123452468

内存快照

const { writeHeapSnapshot } = require('node:v8');
const {
  Worker,
  isMainThread,
  parentPort,
} = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);

  worker.once('message', (filename) => {
    console.log(`worker heapdump: ${filename}`);
    // Now get a heapdump for the main thread.
    console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
  });

  // Tell the worker to create a heapdump.
  worker.postMessage('heapdump');
} else {
  parentPort.once('message', (message) => {
    if (message === 'heapdump') {
      // Generate a heapdump for the worker
      // and return the filename to the parent.
      parentPort.postMessage(writeHeapSnapshot());
    }
  });
} 

参考:https://nodejs.org/api/v8.html#v8writeheapsnapshotfilenameoptions

posted @ 2023-10-12 17:00  地铁程序员  阅读(100)  评论(0编辑  收藏  举报