Skip to content

Commit

Permalink
refactor: update
Browse files Browse the repository at this point in the history
  • Loading branch information
Siumauricio committed Jan 1, 2025
1 parent 36cfacc commit 0a28948
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 14 deletions.
2 changes: 1 addition & 1 deletion apps/monitoring/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ app.use(
);

logServerMetrics();
logContainerMetrics();
// logContainerMetrics();

app.use("/*", cors());
// app.use(
Expand Down
42 changes: 29 additions & 13 deletions apps/monitoring/src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,38 +46,54 @@ const getServerMetrics = async () => {
const REFRESH_RATE_SERVER = Number(process.env.REFRESH_RATE_SERVER || 10000);
const MAX_FILE_SIZE_MB = Number(process.env.MAX_FILE_SIZE_MB || 10); // 10 MB por defecto

const formatMemoryUsage = (data: number) =>
`${Math.round((data / 1024 / 1024) * 100) / 100} MB`;
export function logMemoryUsage(label: string) {
const memoryData = process.memoryUsage();
console.log(`[Memory ${label}]`, {
heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> Actual Memory Used`,
heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> Total Size of the Heap`,
rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size`,
external: `${formatMemoryUsage(memoryData.external)} -> External Memory`,
});
}

logMemoryUsage("Initial");

export const logServerMetrics = () => {
setInterval(async () => {
logMemoryUsage("Before Server Metrics");

const executeMetrics = async () => {
logMemoryUsage("After Server Metrics");
const metrics = await getServerMetrics();

// console.log("Metrics:", metrics);
logMemoryUsage("Before Logging");

const logLine = `${JSON.stringify(metrics)}\n`;

// Verificar si el archivo existe y su tamaño
logMemoryUsage("After Logging");

if (fs.existsSync(serverLogFile)) {
const stats = fs.statSync(serverLogFile);
const fileSizeInMB = stats.size / (1024 * 1024);
// console.log(
// "File size:",
// fileSizeInMB.toFixed(2),
// "MB (max:",
// MAX_FILE_SIZE_MB,
// "MB)",
// );

if (fileSizeInMB >= MAX_FILE_SIZE_MB) {
const fileContent = fs.readFileSync(serverLogFile, "utf-8");
const lines = fileContent.split("\n").filter((line) => line.trim());

const linesToKeep = Math.floor(lines.length / 2);
const newContent = `${lines.slice(-linesToKeep).join("\n")}\n`;
fs.writeFileSync(serverLogFile, newContent);
}
}

fs.appendFile(serverLogFile, logLine, (err) => {
if (err) console.error("Error to write server metrics:", err);
if (err) console.error("Error writing server metrics:", err);
});
}, REFRESH_RATE_SERVER);
logMemoryUsage("After Writing");

// Llama recursivamente después del tiempo establecido
setTimeout(executeMetrics, REFRESH_RATE_SERVER);
};

executeMetrics();
};

0 comments on commit 0a28948

Please sign in to comment.