import { Console } from 'node:console'; import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { Writable } from 'node:stream'; import { app } from 'electron'; export const LAUNCHER_LOG_FILES = [ 'launcher.log', 'launcher.1.log', 'launcher.2.log', 'launcher.3.log', 'launcher.4.log', ] as const; let loggingEnabled = true; let activeLogPath: string | null = null; let fileFailed = false; let originalConsole = console; export function launcherLogFolder(): string { return join(app.getPath('userData'), 'logs'); } function readInitialLoggingEnabled(): boolean { try { const raw = JSON.parse(readFileSync(join(app.getPath('userData'), 'settings.json'), 'utf8')) as { loggingEnabled?: unknown }; return raw?.loggingEnabled !== false; } catch { return true; } } function ensureLogFileReady(): boolean { if (activeLogPath) return !fileFailed; const folder = launcherLogFolder(); const active = join(folder, LAUNCHER_LOG_FILES[0]); try { mkdirSync(folder, { recursive: true }); for (let index = LAUNCHER_LOG_FILES.length - 1; index > 0; index -= 1) { const previous = join(folder, LAUNCHER_LOG_FILES[index - 1]!); if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!)); } writeFileSync(active, '', { flag: 'wx' }); activeLogPath = active; fileFailed = false; return true; } catch (error) { fileFailed = true; originalConsole.error('[logs] opening the launcher log failed:', error); return false; } } /** Enable or disable writing launcher console output to launcher.log at runtime. */ export function setLauncherLoggingEnabled(enabled: boolean): void { loggingEnabled = enabled; if (enabled && !activeLogPath && !fileFailed) { if (ensureLogFileReady()) { console.info(`WTOffline Launcher ${app.getVersion()} logging enabled.`); } } } /** Rotate after taking the single-instance lock and keep the original console destinations. */ export function startLauncherLogging(): void { originalConsole = console; loggingEnabled = readInitialLoggingEnabled(); if (loggingEnabled) ensureLogFileReady(); const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({ write(chunk: Buffer, _encoding, done) { if (loggingEnabled && activeLogPath && !fileFailed) { try { appendFileSync(activeLogPath, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`); } catch (error) { fileFailed = true; originalConsole.error('[logs] writing the launcher log failed:', error); } } destination.write(chunk, done); }, }); globalThis.console = new Console({ stdout: mirror(process.stdout, 'stdout'), stderr: mirror(process.stderr, 'stderr'), }); console.info(`WTOffline Launcher ${app.getVersion()} started.`); }