Add launcher logging and diagnostics export

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 14:45:49 +08:00
1 parent 6ce93ee962
commit 462b49b5c4
11 files changed
+233 -4

No files matched your search

@@ -0,0 +1,86 @@
import { randomUUID } from 'node:crypto';
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { app, dialog, shell, type BrowserWindow } from 'electron';
import { zipSync } from 'fflate';
import { AppError } from '@shared/errors.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
type ArchiveFiles = Record<string, Uint8Array>;
export async function openLogsFolder(): Promise<void> {
const path = launcherLogFolder();
try {
await mkdir(path, { recursive: true });
const failure = await shell.openPath(path);
if (failure) throw new Error(failure);
} catch (error) {
console.warn('[diagnostics] opening the log folder failed:', error);
throw new AppError('logs_folder_open_failed');
}
}
export async function exportDiagnostics(window: BrowserWindow | null): Promise<{ path: string | null }> {
try {
const date = new Date().toISOString().slice(0, 10);
const options = {
defaultPath: `WTOffline-diagnostics-${date}.zip`,
filters: [{ name: 'ZIP', extensions: ['zip'] }],
};
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
if (result.canceled || !result.filePath) return { path: null };
const files: ArchiveFiles = {};
const userData = app.getPath('userData');
await addFile(files, 'settings.json', join(userData, 'settings.json'));
await addFile(files, 'install.json', join(userData, 'install.json'));
const launcherLogs = launcherLogFolder();
if ((await ifPresent(() => lstat(launcherLogs)))?.isDirectory()) {
for (const name of LAUNCHER_LOG_FILES) {
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
}
}
const record = await readInstallRecord();
if (record) await addServerLogs(files, record.dataPath);
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
try {
await writeFile(temporary, zipSync(files), { flag: 'wx' });
await rename(temporary, result.filePath);
} catch (error) {
await rm(temporary, { force: true }).catch(() => undefined);
throw error;
}
return { path: result.filePath };
} catch (error) {
console.error('[diagnostics] exporting the archive failed:', error);
throw new AppError('diagnostics_export_failed');
}
}
/** Include the server's request journals. Traffic bodies can contain player data. */
async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise<void> {
const root = join(dataPath, 'logs');
if (!(await ifPresent(() => lstat(root)))?.isDirectory()) return;
const sessions = await ifPresent(() => readdir(root, { withFileTypes: true }));
for (const session of sessions ?? []) {
if (!session.isDirectory() || !/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/.test(session.name)) continue;
const source = join(root, session.name, 'requests.jsonl');
await addFile(files, `server-logs/${session.name}/requests.jsonl`, source);
}
}
async function addFile(files: ArchiveFiles, entry: string, path: string): Promise<void> {
if (!(await ifPresent(() => lstat(path)))?.isFile()) return;
const bytes = await ifPresent(() => readFile(path));
if (bytes) files[entry] = bytes;
}
async function ifPresent<T>(operation: () => Promise<T>): Promise<T | undefined> {
try {
return await operation();
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
}
@@ -0,0 +1,55 @@
import { Console } from 'node:console';
import { appendFileSync, existsSync, mkdirSync, 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;
export function launcherLogFolder(): string {
return join(app.getPath('userData'), 'logs');
}
/** Rotate after taking the single-instance lock and keep the original console destinations. */
export function startLauncherLogging(): void {
const originalConsole = console;
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' });
} catch (error) {
originalConsole.error('[logs] opening the launcher log failed:', error);
return;
}
let fileFailed = false;
const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({
write(chunk: Buffer, _encoding, done) {
if (!fileFailed) {
try {
appendFileSync(active, `${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.`);
}