express-insights
Version:
Production-ready Express middleware for backend health monitoring with metrics, HTML/JSON output, authentication, and service checks.
114 lines (106 loc) • 3.28 kB
JavaScript
const os = require('os');
const checkDiskSpace = require('check-disk-space').default;
function formatBytes(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
}
function formatUptime(seconds) {
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
return `${days}d ${hours}h ${minutes}m ${secs}s`;
}
async function getDiskUsage() {
try {
const diskPath = os.platform() === 'win32' ? 'C:' : '/';
const diskSpace = await checkDiskSpace(diskPath);
const used = diskSpace.size - diskSpace.free;
return {
total: formatBytes(diskSpace.size),
used: formatBytes(used),
free: formatBytes(diskSpace.free),
usedPercent: diskSpace.size ? ((used / diskSpace.size) * 100).toFixed(2) + '%' : 'N/A',
};
} catch (err) {
return { error: `Disk usage not available: ${err.message}` };
}
}
function getNetworkInterfaces() {
const interfaces = os.networkInterfaces();
const result = {};
for (const [name, addrs] of Object.entries(interfaces)) {
result[name] = addrs
.filter((addr) => !addr.internal)
.map((addr) => ({
address: addr.address,
family: addr.family,
mac: addr.mac,
}));
}
return result;
}
function getProcessInfo() {
return {
pid: process.pid,
ppid: process.ppid,
nodeVersion: process.version,
platform: process.platform,
arch: process.arch,
title: process.title,
argv: process.argv,
execPath: process.execPath,
cwd: process.cwd(),
env: {
NODE_ENV: process.env.NODE_ENV,
PORT: process.env.PORT,
},
};
}
function getEnhancedSystemStats(thresholds) {
const cpus = os.cpus();
const loadavg = os.loadavg();
const memoryUsedPercent = ((os.totalmem() - os.freemem()) / os.totalmem()) * 100;
return {
platform: os.platform(),
type: os.type(),
release: os.release(),
arch: os.arch(),
hostname: os.hostname(),
uptime: formatUptime(os.uptime()),
cpus: {
count: cpus.length,
model: cpus[0]?.model || 'Unknown',
speed: cpus[0]?.speed || 0,
details: cpus.map((cpu) => ({
model: cpu.model,
speed: cpu.speed,
times: cpu.times,
})),
},
memory: {
total: formatBytes(os.totalmem()),
free: formatBytes(os.freemem()),
used: formatBytes(os.totalmem() - os.freemem()),
usedPercent: memoryUsedPercent.toFixed(2) + '%',
alert: memoryUsedPercent > thresholds.memoryUsedPercent ? 'High memory usage' : null,
},
loadavg: {
'1min': loadavg[0].toFixed(2),
'5min': loadavg[1].toFixed(2),
'15min': loadavg[2].toFixed(2),
alert: loadavg[0] > thresholds.cpuLoad1Min ? 'High CPU load' : null,
},
};
}
module.exports = {
formatBytes,
formatUptime,
getDiskUsage,
getNetworkInterfaces,
getProcessInfo,
getEnhancedSystemStats,
};