add 1s cpu usage metric, return standard units of ms and bytes

This commit is contained in:
Alex Holliday committed 2025-07-11 11:23:36 -07:00
1 parent 1cbec8220d
commit b1b4fd3f64
1 file changed
+29 -14
+29 -14
View File
@@ -53,15 +53,34 @@ class DiagnosticController {
} }
} }
async getSystemStats(req, res, next) { async getCPUUsage() {
try {
const startUsage = process.cpuUsage();
await new Promise((resolve) => setTimeout(resolve, 1000));
const endUsage = process.cpuUsage(startUsage);
const cpuUsage = {
userUsageMs: endUsage.user / 1000,
systemUsageMs: endUsage.system / 1000,
usagePercentage: ((endUsage.user + endUsage.system) / 1000 / 1000) * 100,
};
return cpuUsage;
} catch (error) {
return {
userUsageMs: 0,
systemUsageMs: 0,
};
}
}
getSystemStats = async (req, res, next) => {
try { try {
// Memory Usage // Memory Usage
const totalMemory = os.totalmem(); const totalMemory = os.totalmem();
const freeMemory = os.freemem(); const freeMemory = os.freemem();
const osStats = { const osStats = {
freeMemoryMb: freeMemory / 1024 / 1024, // MB freeMemoryBytes: freeMemory, // bytes
totalMemoryMb: totalMemory / 1024 / 1024, // MB totalMemoryBytes: totalMemory, // bytes
}; };
const used = process.memoryUsage(); const used = process.memoryUsage();
@@ -71,18 +90,14 @@ class DiagnosticController {
} }
// CPU Usage // CPU Usage
const cpuUsage = process.cpuUsage(); const cpuMetrics = await this.getCPUUsage();
const cpuMetrics = {
userUsageMs: cpuUsage.user / 1000, // ms
systemUsageMs: cpuUsage.system / 1000, // ms
};
// V8 Heap Statistics // V8 Heap Statistics
const heapStats = v8.getHeapStatistics(); const heapStats = v8.getHeapStatistics();
const v8Metrics = { const v8Metrics = {
totalHeapSizeMb: heapStats.total_heap_size / 1024 / 1024, // MB totalHeapSizeBytes: heapStats.total_heap_size, // bytes
usedHeapSizeMb: heapStats.used_heap_size / 1024 / 1024, // MB usedHeapSizeBytes: heapStats.used_heap_size, // bytes
heapSizeLimitMb: heapStats.heap_size_limit / 1024 / 1024, // MB heapSizeLimitBytes: heapStats.heap_size_limit, // bytes
}; };
// Event Loop Delay // Event Loop Delay
@@ -97,7 +112,7 @@ class DiagnosticController {
} }
// Uptime // Uptime
const uptime = process.uptime(); // seconds const uptimeMs = process.uptime() * 1000; // ms
// Combine Metrics // Combine Metrics
const diagnostics = { const diagnostics = {
@@ -106,7 +121,7 @@ class DiagnosticController {
cpuUsage: cpuMetrics, cpuUsage: cpuMetrics,
v8HeapStats: v8Metrics, v8HeapStats: v8Metrics,
eventLoopDelayMs: eventLoopDelay, eventLoopDelayMs: eventLoopDelay,
uptimeSeconds: uptime, uptimeMs,
}; };
return res.success({ return res.success({
@@ -116,6 +131,6 @@ class DiagnosticController {
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMemoryUsage")); next(handleError(error, SERVICE_NAME, "getMemoryUsage"));
} }
} };
} }
export default DiagnosticController; export default DiagnosticController;