feat(launcher): add logging and diagnostics export

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

No files matched your search

+2
View File
@@ -1,6 +1,7 @@
import { app } from 'electron';
import { registerIpcHandlers } from './ipc/handlers.ts';
import { handleArtProtocol, registerArtScheme } from './services/background-art/art-protocol.ts';
import { startLauncherLogging } from './services/diagnostics/launcher-log.ts';
import { createMainWindow, showMainWindow } from './services/main-window.ts';
/**
@@ -22,6 +23,7 @@ registerArtScheme();
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
startLauncherLogging();
app.on('second-instance', () => showMainWindow());
app.on('window-all-closed', () => app.quit());
// A top-level await on whenReady deadlocks an ESM main entry on Windows.
+4
View File
@@ -3,6 +3,7 @@ import { patchFeatures, recordedGameVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
import { measureFolder } from '../services/game-folder/folder-size.ts';
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
@@ -33,6 +34,9 @@ export function registerIpcHandlers(): void {
if (failure) console.warn('[app] opening the folder failed:', path, failure);
});
handle('app:openLogsFolder', () => openLogsFolder());
handle('app:exportDiagnostics', (_input, sender) => exportDiagnostics(BrowserWindow.fromWebContents(sender)));
handle('window:minimize', (_input, sender) => {
BrowserWindow.fromWebContents(sender)?.minimize();
});
@@ -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.`);
}
+4 -1
View File
@@ -17,6 +17,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts';
import { DiagnosticsSettings } from './pages/settings/DiagnosticsSettings.tsx';
import { GeneralSettings } from './pages/settings/GeneralSettings.tsx';
import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx';
@@ -92,7 +93,9 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
case 'settings':
return {
side: <SubNav sections={SETTINGS_SECTIONS} active={route.settings} label={(section) => t(`settings.sections.${section}`)} onSelect={(section) => go({ page: 'settings', section })} />,
main: <GeneralSettings settings={settings} pictures={backgrounds.pictures} onError={report} />,
main: route.settings === 'diag'
? <DiagnosticsSettings onError={report} />
: <GeneralSettings settings={settings} pictures={backgrounds.pictures} onError={report} />,
bar: home,
};
case 'copies': {
@@ -198,7 +198,17 @@
},
"settings": {
"sections": {
"general": "General"
"general": "General",
"diag": "Diagnostics"
},
"diagnostics": {
"logs": "Logs",
"logsHint": "Logs recorded by the launcher",
"openLogs": "Open log folder",
"export": "Export diagnostics",
"exportHint": "Save logs, settings and the installation record to a ZIP file",
"save": "Export…",
"saved": "Diagnostics saved to {{path}}."
},
"language": "Language",
"languageHint": "Display language of the launcher"
@@ -269,6 +279,8 @@
},
"errors": {
"internal_error": "An internal launcher error occurred.",
"logs_folder_open_failed": "The launcher log folder could not be opened.",
"diagnostics_export_failed": "The diagnostics archive could not be saved.",
"settings_write_failed": "The settings could not be saved.",
"folder_unreadable": "The folder cannot be read: {{path}}",
"not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}",
@@ -198,7 +198,17 @@
},
"settings": {
"sections": {
"general": "常规"
"general": "常规",
"diag": "诊断"
},
"diagnostics": {
"logs": "日志",
"logsHint": "启动器运行日志",
"openLogs": "打开日志文件夹",
"export": "导出诊断信息",
"exportHint": "导出包含日志、设置和安装记录的 ZIP 文件",
"save": "导出…",
"saved": "诊断信息已保存到 {{path}}。"
},
"language": "语言",
"languageHint": "启动器界面的显示语言"
@@ -269,6 +279,8 @@
},
"errors": {
"internal_error": "启动器内部错误。",
"logs_folder_open_failed": "无法打开启动器日志文件夹。",
"diagnostics_export_failed": "无法保存诊断信息。",
"settings_write_failed": "无法保存设置。",
"folder_unreadable": "无法读取文件夹:{{path}}",
"not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}",
@@ -0,0 +1,44 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
interface DiagnosticsSettingsProps {
readonly onError: (error: unknown) => void;
}
export function DiagnosticsSettings({ onError }: DiagnosticsSettingsProps) {
const { t } = useTranslation();
const [exporting, setExporting] = useState(false);
const [savedPath, setSavedPath] = useState<string | null>(null);
async function save(): Promise<void> {
setExporting(true);
setSavedPath(null);
try {
const result = await ipcInvoke('app:exportDiagnostics');
setSavedPath(result.path);
} catch (error) {
onError(error);
} finally {
setExporting(false);
}
}
return (
<Sheet title={t('settings.sections.diag')}>
<Row label={t('settings.diagnostics.logs')} hint={t('settings.diagnostics.logsHint')}>
<button type="button" className="button" onClick={() => ipcInvoke('app:openLogsFolder').catch(onError)}>
{t('settings.diagnostics.openLogs')}
</button>
</Row>
<Row label={t('settings.diagnostics.export')} hint={t('settings.diagnostics.exportHint')}>
<button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}>
{t('settings.diagnostics.save')}
</button>
</Row>
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</Sheet>
);
}
@@ -9,7 +9,7 @@ export type PageId = (typeof PAGES)[number];
export const COPY_SECTIONS = ['summary', 'features'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number];
export const SETTINGS_SECTIONS = ['general'] as const;
export const SETTINGS_SECTIONS = ['general', 'diag'] as const;
export type SettingsSection = (typeof SETTINGS_SECTIONS)[number];
export interface Route {
+2
View File
@@ -14,6 +14,8 @@ export const APP_ERROR_CODES = [
'internal_error',
/** The launcher's own settings file could not be written. */
'settings_write_failed',
'logs_folder_open_failed',
'diagnostics_export_failed',
/** A folder the player chose does not exist or cannot be read (params: path). */
'folder_unreadable',
/** The chosen folder lacks the files of a War Thunder installation (params: path). */
+9
View File
@@ -42,6 +42,15 @@ export const ipcContract = {
input: z.object({ path: z.string().min(1) }),
output: z.void(),
},
'app:openLogsFolder': {
input: z.void(),
output: z.void(),
},
'app:exportDiagnostics': {
input: z.void(),
/** The saved archive, or null when the player cancelled. */
output: z.object({ path: z.string().nullable() }),
},
'dialog:pickFolder': {
/** The dialog title, already translated by the window. */
input: z.object({ title: z.string().optional() }),