Skip to content

Commit

Permalink
Add logging messages to simplify CPU profiling
Browse files Browse the repository at this point in the history
  • Loading branch information
dokmic committed Jan 22, 2025
1 parent 0591605 commit 89e4222
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/cli/profiler/profiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,19 @@ import { join } from 'path';
import { Session } from 'node:inspector';
import { threadId } from 'node:worker_threads';
import { promisify } from 'util';
import { Logger } from '../logger';

class Profiler {
#counter = 0;
#logger;
#path;
#session;

constructor() {
constructor(logger) {
const execOpts = getopts(process.execArgv);
const envOpts = getopts(process.env.NODE_OPTIONS ? process.env.NODE_OPTIONS.split(/\s+/) : []);
this.#path = execOpts['diagnostic-dir'] || envOpts['diagnostic-dir'] || process.cwd();
this.#logger = logger;
}

#getPath() {
Expand Down Expand Up @@ -51,13 +54,17 @@ class Profiler {

await promisify(this.#session.post)('Profiler.enable');
await promisify(this.#session.post)('Profiler.start');
this.#logger.log(`CPU profiling is started for process '${process.pid}'.`);
}

async #stop() {
try {
const { profile } = await promisify(this.#session.post)('Profiler.stop');
this.#logger.log(`CPU profiling is stopped for process '${process.pid}'.`);

const path = this.#getPath();
await promisify(writeFile)(path, JSON.stringify(profile));
this.#logger.log(`Saved CPU profile to '${path}'.`);
} finally {
this.#session.disconnect();
this.#session = undefined;
Expand All @@ -81,8 +88,10 @@ export default function (program) {
return;
}

const profiler = new Profiler();
const logger = new Logger();
const profiler = new Profiler(logger);
process.removeAllListeners(signal);
process.on(signal, profiler.toggle.bind(profiler));
logger.log(`CPU profiling is enabled on '${signal}' for process '${process.pid}'.`);
});
}

0 comments on commit 89e4222

Please sign in to comment.