import { app } from "electron"; import * as fs from "fs"; import * as path from "path"; export class LogService { private static instance: LogService; private logPath: string; private constructor() { // Create logs directory in userData const userDataPath = app.getPath("userData"); const logsDir = path.join(userDataPath, "logs"); if (!fs.existsSync(logsDir)) { fs.mkdirSync(logsDir, { recursive: true }); } // Monthly log file const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, "0"); const monthString = `${year}-${month}`; // YYYY-MM this.logPath = path.join(logsDir, `app_${monthString}.log`); this.info(`--- Log initialized at ${now.toISOString()} ---`); console.log(`Log file: ${this.logPath}`); } /** * Garantizar que sea singleton * @returns */ public static getInstance(): LogService { if (!LogService.instance) { LogService.instance = new LogService(); } return LogService.instance; } public info(message: string): void { this.write("INFO", message); } public error(message: string, error?: unknown): void { const errorDetail = error ? ` | Details: ${JSON.stringify(error)}` : ""; this.write("ERROR", `${message}${errorDetail}`); } public logOperation( operation: string, data: unknown, result?: unknown, ): void { const entry = { operation, data, result, timestamp: new Date().toISOString(), }; this.write("OP", JSON.stringify(entry)); } private write(level: string, message: string): void { const timestamp = new Date().toISOString(); const logEntry = `[${timestamp}] [${level}] ${message}\n`; try { fs.appendFileSync(this.logPath, logEntry, "utf8"); } catch (err) { console.error("Failed to write to log file:", err); } } } export const logger = LogService.getInstance();