89 lines
2.4 KiB
JavaScript
89 lines
2.4 KiB
JavaScript
import { readFileSync, writeFileSync, existsSync, statSync } from 'fs';
|
|
import { join } from 'path';
|
|
import { PATHS } from '../config/constants.js';
|
|
|
|
// Función para obtener la ruta del log (en Docker puede estar en /data/logs)
|
|
export function getLogPath() {
|
|
const logsDirPath = join(PATHS.PROJECT_ROOT, 'logs', 'monitor.log');
|
|
const rootLogPath = join(PATHS.PROJECT_ROOT, 'monitor.log');
|
|
|
|
if (existsSync(logsDirPath)) {
|
|
return logsDirPath;
|
|
}
|
|
return rootLogPath;
|
|
}
|
|
|
|
// Leer archivo JSON de forma segura
|
|
export function readJSON(path, defaultValue = {}) {
|
|
try {
|
|
if (existsSync(path)) {
|
|
return JSON.parse(readFileSync(path, 'utf8'));
|
|
}
|
|
return defaultValue;
|
|
} catch (error) {
|
|
console.error(`Error leyendo ${path}:`, error.message);
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
// Escribir archivo JSON
|
|
export function writeJSON(path, data) {
|
|
try {
|
|
writeFileSync(path, JSON.stringify(data, null, 2), 'utf8');
|
|
return true;
|
|
} catch (error) {
|
|
console.error(`Error escribiendo ${path}:`, error.message);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Leer logs de forma segura
|
|
export function readLogs(logPath, options = {}) {
|
|
const { sinceLine = 0, limit = 500 } = options;
|
|
|
|
try {
|
|
if (!existsSync(logPath)) {
|
|
return { logs: [], totalLines: 0, lastLineNumber: 0 };
|
|
}
|
|
|
|
// Verificar que no sea un directorio
|
|
try {
|
|
const stats = statSync(logPath);
|
|
if (stats.isDirectory()) {
|
|
return {
|
|
logs: ['Error: monitor.log es un directorio. Por favor, elimínalo y reinicia.'],
|
|
totalLines: 0,
|
|
lastLineNumber: 0
|
|
};
|
|
}
|
|
} catch (e) {
|
|
return { logs: [], totalLines: 0, lastLineNumber: 0 };
|
|
}
|
|
|
|
const logsContent = readFileSync(logPath, 'utf8');
|
|
const allLines = logsContent.split('\n').filter(l => l.trim());
|
|
const totalLines = allLines.length;
|
|
|
|
if (sinceLine > 0 && sinceLine < totalLines) {
|
|
// Devolver solo las líneas nuevas después de sinceLine
|
|
const newLines = allLines.slice(sinceLine);
|
|
return {
|
|
logs: newLines,
|
|
totalLines: totalLines,
|
|
lastLineNumber: totalLines - 1
|
|
};
|
|
} else {
|
|
// Carga inicial: devolver las últimas líneas
|
|
const lastLines = allLines.slice(-limit);
|
|
return {
|
|
logs: lastLines,
|
|
totalLines: totalLines,
|
|
lastLineNumber: totalLines - 1
|
|
};
|
|
}
|
|
} catch (error) {
|
|
throw new Error(error.message);
|
|
}
|
|
}
|
|
|