|
| 1 | +import * as fs from "fs" |
| 2 | +import * as path from "path" |
| 3 | +import { createWriteStream, WriteStream } from "fs" |
| 4 | + |
| 5 | +export type LogLevel = "INFO" | "WARN" | "ERROR" | "DEBUG" |
| 6 | + |
| 7 | +export interface LogMetadata { |
| 8 | + [key: string]: any |
| 9 | +} |
| 10 | + |
| 11 | +export interface LogEntry { |
| 12 | + timestamp: string |
| 13 | + level: LogLevel |
| 14 | + component: string |
| 15 | + message: string |
| 16 | + metadata?: LogMetadata |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * FileLogger - Système de journalisation persistante pour diagnostic des crashes webview |
| 21 | + * |
| 22 | + * Fonctionnalités : |
| 23 | + * - Logging persistant survit aux crashes de webview |
| 24 | + * - Support des niveaux de log (INFO, WARN, ERROR, DEBUG) |
| 25 | + * - Métadonnées structurées pour contexte enrichi |
| 26 | + * - Rotation automatique des logs si taille dépassée |
| 27 | + * - Thread-safe avec gestion d'erreurs gracieuse |
| 28 | + */ |
| 29 | +export class FileLogger { |
| 30 | + private logFilePath: string |
| 31 | + private logStream?: WriteStream |
| 32 | + private isInitialized: boolean = false |
| 33 | + private writeQueue: string[] = [] |
| 34 | + private isWriting: boolean = false |
| 35 | + private maxLogFileSize: number = 10 * 1024 * 1024 // 10MB par défaut |
| 36 | + private maxLogFiles: number = 5 |
| 37 | + |
| 38 | + constructor(baseDir: string, filename: string = "roo-code-debug.log") { |
| 39 | + // Créer le répertoire .logs dans le baseDir |
| 40 | + const logsDir = path.join(baseDir, ".logs") |
| 41 | + this.logFilePath = path.join(logsDir, filename) |
| 42 | + |
| 43 | + // Initialisation asynchrone pour éviter de bloquer le constructeur |
| 44 | + this.initialize().catch((error) => { |
| 45 | + console.error(`[FileLogger] Failed to initialize: ${error}`) |
| 46 | + }) |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Initialise le logger et crée le répertoire si nécessaire |
| 51 | + */ |
| 52 | + private async initialize(): Promise<void> { |
| 53 | + try { |
| 54 | + // Créer le répertoire .logs s'il n'existe pas |
| 55 | + const logsDir = path.dirname(this.logFilePath) |
| 56 | + await fs.promises.mkdir(logsDir, { recursive: true }) |
| 57 | + |
| 58 | + // Vérifier si rotation nécessaire |
| 59 | + await this.checkAndRotateLog() |
| 60 | + |
| 61 | + // Créer le stream de log |
| 62 | + this.logStream = createWriteStream(this.logFilePath, { flags: "a", encoding: "utf8" }) |
| 63 | + |
| 64 | + // Gérer les erreurs du stream |
| 65 | + this.logStream.on("error", (error) => { |
| 66 | + console.error(`[FileLogger] Stream error: ${error}`) |
| 67 | + }) |
| 68 | + |
| 69 | + this.isInitialized = true |
| 70 | + |
| 71 | + // Écrire les messages en attente |
| 72 | + await this.processWriteQueue() |
| 73 | + |
| 74 | + // Log d'initialisation |
| 75 | + await this.log("INFO", "FILE_LOGGER", "FileLogger initialized successfully", { |
| 76 | + logFilePath: this.logFilePath, |
| 77 | + timestamp: new Date().toISOString(), |
| 78 | + }) |
| 79 | + } catch (error) { |
| 80 | + console.error(`[FileLogger] Initialization failed: ${error}`) |
| 81 | + this.isInitialized = false |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Vérifie la taille du fichier log et effectue une rotation si nécessaire |
| 87 | + */ |
| 88 | + private async checkAndRotateLog(): Promise<void> { |
| 89 | + try { |
| 90 | + const stats = await fs.promises.stat(this.logFilePath) |
| 91 | + |
| 92 | + if (stats.size > this.maxLogFileSize) { |
| 93 | + await this.rotateLogFiles() |
| 94 | + } |
| 95 | + } catch (error) { |
| 96 | + // Fichier n'existe pas encore, pas d'action nécessaire |
| 97 | + if (error.code !== "ENOENT") { |
| 98 | + console.error(`[FileLogger] Error checking log file size: ${error}`) |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * Effectue la rotation des fichiers de log |
| 105 | + */ |
| 106 | + private async rotateLogFiles(): Promise<void> { |
| 107 | + try { |
| 108 | + const baseFilename = this.logFilePath |
| 109 | + const dir = path.dirname(baseFilename) |
| 110 | + const ext = path.extname(baseFilename) |
| 111 | + const name = path.basename(baseFilename, ext) |
| 112 | + |
| 113 | + // Décaler les fichiers existants (.1 -> .2, .2 -> .3, etc.) |
| 114 | + for (let i = this.maxLogFiles - 1; i >= 1; i--) { |
| 115 | + const currentFile = path.join(dir, `${name}.${i}${ext}`) |
| 116 | + const nextFile = path.join(dir, `${name}.${i + 1}${ext}`) |
| 117 | + |
| 118 | + try { |
| 119 | + await fs.promises.access(currentFile) |
| 120 | + if (i === this.maxLogFiles - 1) { |
| 121 | + // Supprimer le plus ancien |
| 122 | + await fs.promises.unlink(currentFile) |
| 123 | + } else { |
| 124 | + // Renommer vers le suivant |
| 125 | + await fs.promises.rename(currentFile, nextFile) |
| 126 | + } |
| 127 | + } catch { |
| 128 | + // Fichier n'existe pas, continuer |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + // Renommer le fichier actuel vers .1 |
| 133 | + const rotatedFile = path.join(dir, `${name}.1${ext}`) |
| 134 | + try { |
| 135 | + await fs.promises.rename(baseFilename, rotatedFile) |
| 136 | + } catch (error) { |
| 137 | + console.error(`[FileLogger] Error rotating main log file: ${error}`) |
| 138 | + } |
| 139 | + } catch (error) { |
| 140 | + console.error(`[FileLogger] Error during log rotation: ${error}`) |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + /** |
| 145 | + * Traite la queue d'écriture |
| 146 | + */ |
| 147 | + private async processWriteQueue(): Promise<void> { |
| 148 | + if (this.isWriting || !this.isInitialized || this.writeQueue.length === 0) { |
| 149 | + return |
| 150 | + } |
| 151 | + |
| 152 | + this.isWriting = true |
| 153 | + |
| 154 | + try { |
| 155 | + while (this.writeQueue.length > 0) { |
| 156 | + const logLine = this.writeQueue.shift() |
| 157 | + if (logLine && this.logStream) { |
| 158 | + await new Promise<void>((resolve, reject) => { |
| 159 | + this.logStream!.write(logLine, (error) => { |
| 160 | + if (error) reject(error) |
| 161 | + else resolve() |
| 162 | + }) |
| 163 | + }) |
| 164 | + } |
| 165 | + } |
| 166 | + } catch (error) { |
| 167 | + console.error(`[FileLogger] Error processing write queue: ${error}`) |
| 168 | + } finally { |
| 169 | + this.isWriting = false |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + /** |
| 174 | + * Log un message avec le niveau spécifié |
| 175 | + */ |
| 176 | + async log(level: LogLevel, component: string, message: string, metadata?: LogMetadata): Promise<void> { |
| 177 | + const logEntry: LogEntry = { |
| 178 | + timestamp: new Date().toISOString(), |
| 179 | + level, |
| 180 | + component, |
| 181 | + message, |
| 182 | + metadata, |
| 183 | + } |
| 184 | + |
| 185 | + // Formatter la ligne de log |
| 186 | + const logLine = this.formatLogEntry(logEntry) |
| 187 | + |
| 188 | + // Ajouter à la queue |
| 189 | + this.writeQueue.push(logLine) |
| 190 | + |
| 191 | + // Traiter la queue si possible |
| 192 | + if (this.isInitialized) { |
| 193 | + await this.processWriteQueue() |
| 194 | + } |
| 195 | + |
| 196 | + // Aussi logger dans la console pour les erreurs |
| 197 | + if (level === "ERROR" || level === "WARN") { |
| 198 | + console.log(`[${level}] ${component}: ${message}`, metadata || "") |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + /** |
| 203 | + * Formate une entrée de log en ligne de texte |
| 204 | + */ |
| 205 | + private formatLogEntry(entry: LogEntry): string { |
| 206 | + const metadataStr = entry.metadata ? ` | ${JSON.stringify(entry.metadata)}` : "" |
| 207 | + return `[${entry.timestamp}] ${entry.level} ${entry.component}: ${entry.message}${metadataStr}\n` |
| 208 | + } |
| 209 | + |
| 210 | + /** |
| 211 | + * Méthodes de convenance pour chaque niveau |
| 212 | + */ |
| 213 | + async info(component: string, message: string, metadata?: LogMetadata): Promise<void> { |
| 214 | + return this.log("INFO", component, message, metadata) |
| 215 | + } |
| 216 | + |
| 217 | + async warn(component: string, message: string, metadata?: LogMetadata): Promise<void> { |
| 218 | + return this.log("WARN", component, message, metadata) |
| 219 | + } |
| 220 | + |
| 221 | + async error(component: string, message: string, metadata?: LogMetadata): Promise<void> { |
| 222 | + return this.log("ERROR", component, message, metadata) |
| 223 | + } |
| 224 | + |
| 225 | + async debug(component: string, message: string, metadata?: LogMetadata): Promise<void> { |
| 226 | + return this.log("DEBUG", component, message, metadata) |
| 227 | + } |
| 228 | + |
| 229 | + /** |
| 230 | + * Force l'écriture de tous les logs en attente et ferme le stream |
| 231 | + */ |
| 232 | + async dispose(): Promise<void> { |
| 233 | + try { |
| 234 | + // Traiter tous les messages en attente |
| 235 | + await this.processWriteQueue() |
| 236 | + |
| 237 | + // Log de fermeture |
| 238 | + if (this.isInitialized) { |
| 239 | + await this.log("INFO", "FILE_LOGGER", "FileLogger disposing", { |
| 240 | + pendingMessages: this.writeQueue.length, |
| 241 | + }) |
| 242 | + } |
| 243 | + |
| 244 | + // Fermer le stream |
| 245 | + if (this.logStream) { |
| 246 | + await new Promise<void>((resolve, reject) => { |
| 247 | + this.logStream!.end((error: any) => { |
| 248 | + if (error) reject(error) |
| 249 | + else resolve() |
| 250 | + }) |
| 251 | + }) |
| 252 | + this.logStream = undefined |
| 253 | + } |
| 254 | + |
| 255 | + this.isInitialized = false |
| 256 | + } catch (error) { |
| 257 | + console.error(`[FileLogger] Error during disposal: ${error}`) |
| 258 | + } |
| 259 | + } |
| 260 | + |
| 261 | + /** |
| 262 | + * Retourne le chemin du fichier de log actuel |
| 263 | + */ |
| 264 | + getLogFilePath(): string { |
| 265 | + return this.logFilePath |
| 266 | + } |
| 267 | + |
| 268 | + /** |
| 269 | + * Vérifie si le logger est initialisé |
| 270 | + */ |
| 271 | + isReady(): boolean { |
| 272 | + return this.isInitialized |
| 273 | + } |
| 274 | +} |
0 commit comments