Skip to content

Instantly share code, notes, and snippets.

@aspen-roller
Created December 3, 2020 20:35
Show Gist options
  • Save aspen-roller/0ee034df0053d02ce7cd34414d1fe298 to your computer and use it in GitHub Desktop.
Save aspen-roller/0ee034df0053d02ce7cd34414d1fe298 to your computer and use it in GitHub Desktop.
automatically record heapdump snapshots in node.js #nodejs #debug #util
'use strict';
/* eslint-disable no-console */
// NOTE: update the debug scope
const debug = require('debug')('recordHeapdump');
const heapdump = require('heapdump');
var interval;
var nextThreshold_MB = 0;
module.exports = recordHeapdump;
/**
* Automatically records a heapdump snapshot to the local temp directory
* for a given memory size threshold.
* @param {number} threshold_MB Delta between snapshot sizes
* @param {number} interval_ms How often to check the memory for a snapshot
*/
function recordHeapdump(threshold_MB=100, interval_ms=1000 * 2) {
if (interval) {
clearInterval(interval);
}
interval = setInterval(function heapdumpInterval() {
var rss_MB = process.memoryUsage().rss / (1 << 20);
debug('rss_MB:', rss_MB.toString().padEnd(12), 'nextThreshold_MB:', nextThreshold_MB);
if (rss_MB > nextThreshold_MB) {
heapdump.writeSnapshot(`temp/${Date.now()}.heapsnapshot`, (err, filename) => {
if (err) {
console.error('heapsnapshot error', err);
} else {
console.log(`wrote heapsnapshot ${filename}, rss: ${rss_MB} MB`);
}
});
nextThreshold_MB += threshold_MB;
}
}, interval_ms);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment