All files / src/utils logger.js

100% Statements 208/208
100% Branches 33/33
100% Functions 13/13
100% Lines 208/208

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 20914x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 2x 2x 13x 13x 13x 13x 13x 13x 13x 14x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 13x 13x 13x 13x 13x 13x 3x 2x 2x 2x 2x 2x 1x 1x 2x 13x 13x 1x 1x 13x 14x 14x 14x 14x 14x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 8x 8x 8x 8x 3x 1x 3x 1x 1x 1x 1x 3x 8x 14x 14x 14x 14x 14x 3x 3x 14x 14x 14x 14x 14x 1x 1x 14x 14x 14x 14x 14x 1x 1x 14x 14x 14x 14x 14x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 14x 14x 14x 14x 14x 1x 1x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 6x 6x 14x 14x 14x 14x 14x 2x 1x 1x 1x 1x 1x 1x 1x 2x 14x 14x 14x 14x 14x 2x 1x 1x 1x 2x 14x 14x 14x  
const vscode = require("vscode");
const fs = require("fs");
const path = require("path");
 
/**
 * Logger mejorado para la extensión G-Bot
 *
 * Características:
 * - Escribe a Output Channel (visible en VS Code)
 * - Escribe a archivo .log en disco
 * - Auto-muestra el Output Channel al iniciar operación
 * - Limpia logs antiguos automáticamente (más de 7 días)
 * - Soporta múltiples niveles: info, warn, error
 */
class Logger {
  /**
   * @param {vscode.ExtensionContext} context - Contexto de la extensión
   */
  constructor(context) {
    this.outputChannel = vscode.window.createOutputChannel("G-Bot");
    this.context = context;
    this.logFilePath = null;
    this.autoShowOutput = true; // Auto-mostrar Output Channel
 
    // Crear carpeta de logs
    this._setupLogFile();
  }
 
  /**
   * Configura archivo de log en disco
   * @private
   */
  _setupLogFile() {
    try {
      // Usar carpeta de la extensión
      const logDir = this.context
        ? path.join(this.context.extensionPath, "logs")
        : path.join(__dirname, "..", "..", "logs");
 
      // Crear carpeta si no existe
      if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir, { recursive: true });
      }
 
      // Nombre de archivo con fecha
      const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD
      this.logFilePath = path.join(logDir, `G-Bot-${today}.log`);
 
      // Limpiar logs antiguos (más de 7 días)
      this._cleanOldLogs(logDir, 7);
    } catch (error) {
      console.error("Error configurando log file:", error);
      // No lanzar error, solo registrar - el logger puede funcionar sin archivo
      this.logFilePath = null;
    }
  }
 
  /**
   * Limpia logs antiguos
   */
  _cleanOldLogs(logDir, daysToKeep) {
    try {
      const files = fs.readdirSync(logDir);
      const now = Date.now();
      const maxAge = daysToKeep * 24 * 60 * 60 * 1000; // días a ms
 
      files.forEach((file) => {
        if (file.endsWith(".log")) {
          const filePath = path.join(logDir, file);
          const stat = fs.statSync(filePath);
          const age = now - stat.mtime.getTime();
 
          if (age > maxAge) {
            fs.unlinkSync(filePath);
          }
        }
      });
    } catch (error) {
      console.error("Error limpiando logs antiguos:", error);
    }
  }
 
  /**
   * Escribe mensaje a Output Channel y archivo
   */
  _write(level, message, showToUser = false) {
    // Sanitizar mensaje para prevenir inyección de logs
    const sanitizedMessage =
      typeof message === "string"
        ? message.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "")
        : String(message);
 
    const timestamp = new Date().toLocaleTimeString();
    const fullTimestamp = new Date().toISOString();
    const formattedMessage = `[${timestamp}] ${sanitizedMessage}`;
    const fileMessage = `[${fullTimestamp}] [${level}] ${sanitizedMessage}`;
 
    // Output Channel (VS Code)
    this.outputChannel.appendLine(formattedMessage);
 
    // Archivo en disco
    if (this.logFilePath) {
      try {
        fs.appendFileSync(this.logFilePath, fileMessage + "\n");
      } catch (error) {
        console.error("Error escribiendo a log file:", error);
      }
    }
 
    // Mostrar como notificación si es importante
    if (showToUser) {
      if (level === "ERROR") {
        vscode.window.showErrorMessage(`G-Bot: ${message}`);
      } else if (level === "WARN") {
        vscode.window.showWarningMessage(`G-Bot: ${message}`);
      } else {
        vscode.window.showInformationMessage(`G-Bot: ${message}`);
      }
    }
  }
 
  /**
   * Log información
   */
  info(message, showToUser = false) {
    this._write("INFO", message, showToUser);
  }
 
  /**
   * Log error
   */
  error(message, showToUser = true) {
    this._write("ERROR", `❌ ${message}`, showToUser);
  }
 
  /**
   * Log warning
   */
  warn(message, showToUser = false) {
    this._write("WARN", `⚠ ${message}`, showToUser);
  }
 
  /**
   * Log debug (solo en archivo, no en Output Channel)
   */
  debug(message) {
    if (this.logFilePath) {
      const timestamp = new Date().toISOString();
      const fileMessage = `[${timestamp}] [DEBUG] ${message}\n`;
      try {
        fs.appendFileSync(this.logFilePath, fileMessage);
      } catch (error) {
        console.error("Error escribiendo debug:", error);
      }
    }
  }
 
  /**
   * Muestra el output channel (automático al iniciar operación)
   */
  show(preserveFocus = false) {
    this.outputChannel.show(preserveFocus);
  }
 
  /**
   * Limpia el output channel
   */
  clear() {
    this.outputChannel.clear();
    this.info("=== Nueva sesión iniciada ===");
    if (this.logFilePath) {
      this.info(`Log file: ${this.logFilePath}`);
    }
  }
 
  /**
   * Obtiene ruta del archivo de log actual
   */
  getLogFilePath() {
    return this.logFilePath;
  }
 
  /**
   * Abre el archivo de log en VS Code
   */
  async openLogFile() {
    if (this.logFilePath && fs.existsSync(this.logFilePath)) {
      const document = await vscode.workspace.openTextDocument(
        this.logFilePath
      );
      await vscode.window.showTextDocument(document);
    } else {
      vscode.window.showWarningMessage("No se encontró el archivo de log");
    }
  }
 
  /**
   * Copia ruta del log al clipboard
   */
  copyLogPathToClipboard() {
    if (this.logFilePath) {
      vscode.env.clipboard.writeText(this.logFilePath);
      vscode.window.showInformationMessage(`Ruta copiada: ${this.logFilePath}`);
    }
  }
}
 
module.exports = { Logger };