feat(launcher): add About log export shortcut and runtime logging toggle
Launcher release / release (push) Waiting to run

Add a quick ZIP log export button to the About page (also bundling the latest embedded browser -browser.log while excluding player saves) and add a runtime logging toggle under Settings -> Diagnostics that controls launcher file logs, local server traffic logs, and wto_ws.log via log=0 in wto_ws.cfg. Update the v0.1.2 release note accordingly.
This commit is contained in:
N0VAN0M4LY committed 2026-12-02 17:41:49 +08:00
1 parent 2d5e268083
commit fb7d07f4f9
21 files changed
+230 -37

No files matched your search

+2
View File
@@ -6,6 +6,7 @@
- **省空间复制改为跨版本规则。** 取消原先绑定单一版本号(`2.61.0.43`)与 8 MiB 体积门槛的静态哈希清单,改为基于只读资源规则自动共用 `content/` 与 `content.hq/` 下的 `.dxp.bin` 和 `.grp` 资源包;小版本更新后无需等待新清单即可继续省空间安装或转换,且同卷省空间客户端执行「从在线版更新」时会保持或重建硬链接,不再拆分为完整复制。
- **修复维护页「从在线版更新」误报路径越界。** 扫描安装来源时排除顶层残留的 `wtoffline` 目录;安装向导第 3 步与后台同步拦截将数据目录设为客户端目录或其父目录的配置,并解除旧安装把数据目录放在客户端父目录时的误报;所有路径安全校验失败均在启动器日志中记录具体原因与路径以便排查。
- **「关于」页快速导出日志与关闭日志开关。** 在「关于」页新增「保存日志 ZIP…」快捷按钮(导出内容同时纳入最新一份内置浏览器 `-browser.log`,仍不含玩家存档),并在「设置 → 诊断」新增「生成运行日志」开关,允许关闭启动器日志、本地服务器流量日志及 `wto_ws.log` 的磁盘写入。
### 客户端兼容性
@@ -19,6 +20,7 @@
- **Version-independent space-saving copies.** Replaced the single-version (`2.61.0.43`) SHA-256 manifest and 8 MiB cutoff with declarative read-only asset rules covering `.dxp.bin` and `.grp` archives under `content/` and `content.hq/`. Space-saving installs and conversions now keep working across minor updates, and updating a same-volume space-saving client preserves or recreates hard links instead of detaching them into full copies.
- **Fix false `maintenance_location` errors when updating.** Ignore stray top-level `wtoffline` folders when scanning a stock source, prevent picking a data folder that equals or contains the client folder during installation (with inline Step 3 validation), stop blocking updates when an existing installation placed `dataPath` at an ancestor of the client folder, and log the exact reason and paths on every path-scope rejection.
- **Quick log ZIP export on About and runtime logging toggle.** Added a quick "Save log ZIP…" button on the About page (now also bundling the latest embedded browser `-browser.log`, still excluding saves), and added a "Record runtime logs" toggle under Settings → Diagnostics to stop writing launcher logs, local server traffic logs, and `wto_ws.log`.
### Client compatibility
@@ -4,6 +4,7 @@ import { app } from 'electron';
import { AppError } from '@shared/errors.ts';
import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts';
/**
* The launcher's settings file, `<user data>/settings.json`. Read once and cached; every change is
@@ -47,6 +48,7 @@ export function updateSettings(patch: SettingsPatch): Promise<Settings> {
throw new AppError('settings_write_failed');
}
cached = merged;
setLauncherLoggingEnabled(merged.loggingEnabled);
return merged;
});
pending = operation.then(() => undefined, () => undefined);
@@ -61,7 +61,7 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
if (dataPath) await addServerLogs(files, dataPath);
if (record) await addClientLogs(files, record);
if (record) await addClientLogs(files, record, settings.loggingEnabled);
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
try {
@@ -91,10 +91,11 @@ async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise<voi
}
/**
* Include the hook library log, the latest game .clog and a small metadata summary for the active
* client so startup crashes can be diagnosed without touching player saves.
* Include the hook library log, the latest game .clog and embedded browser log, and a small
* metadata summary for the active client so crashes and web-UI issues can be diagnosed without
* touching player saves.
*/
async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promise<void> {
async function addClientLogs(files: ArchiveFiles, record: InstallRecord, loggingEnabled: boolean): Promise<void> {
const exeFolder = join(record.copyPath, dirname(GAME_FILES.executable));
const hookLogPath = join(exeFolder, HOOK_LOG_FILENAME);
const hookConfigPath = join(exeFolder, HOOK_CONFIG_FILENAME);
@@ -117,6 +118,9 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis
let latestClog: ListedFile | null = null;
let latestClogIncluded = false;
let latestClogOmittedReason: string | null = null;
let latestBrowserLog: ListedFile | null = null;
let latestBrowserLogIncluded = false;
let latestBrowserLogOmittedReason: string | null = null;
const gameLogsDirStat = await safeStat(gameLogsFolder);
if (gameLogsDirStat?.isDirectory()) {
@@ -149,11 +153,28 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis
latestClogIncluded = added.included;
latestClogOmittedReason = added.omittedReason;
}
const newestBrowserLog = inspected.find((item) => item.name.toLowerCase().endsWith('-browser.log')) ?? null;
if (newestBrowserLog) {
latestBrowserLog = {
name: newestBrowserLog.name,
size: newestBrowserLog.size,
modifiedAt: newestBrowserLog.modifiedAt,
};
const added = await addBoundedClientFile(
files,
`client-logs/game-logs/${newestBrowserLog.name}`,
join(gameLogsFolder, newestBrowserLog.name),
newestBrowserLog.size,
);
latestBrowserLogIncluded = added.included;
latestBrowserLogOmittedReason = added.omittedReason;
}
}
const summary = {
exportedAt: new Date().toISOString(),
launcherVersion: app.getVersion(),
loggingEnabled,
platform: process.platform,
arch: process.arch,
osRelease: release(),
@@ -180,6 +201,13 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis
...(latestClogOmittedReason ? { omittedReason: latestClogOmittedReason } : {}),
}
: null,
latestBrowserLog: latestBrowserLog
? {
...latestBrowserLog,
included: latestBrowserLogIncluded,
...(latestBrowserLogOmittedReason ? { omittedReason: latestBrowserLogOmittedReason } : {}),
}
: null,
};
files['client-logs/summary.json'] = new TextEncoder().encode(`${JSON.stringify(summary, null, 2)}\n`);
}
@@ -1,5 +1,5 @@
import { Console } from 'node:console';
import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { Writable } from 'node:stream';
import { app } from 'electron';
@@ -12,13 +12,26 @@ export const LAUNCHER_LOG_FILES = [
'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');
}
/** Rotate after taking the single-instance lock and keep the original console destinations. */
export function startLauncherLogging(): void {
const originalConsole = console;
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 {
@@ -28,17 +41,37 @@ export function startLauncherLogging(): void {
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;
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();
let fileFailed = false;
const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({
write(chunk: Buffer, _encoding, done) {
if (!fileFailed) {
if (loggingEnabled && activeLogPath && !fileFailed) {
try {
appendFileSync(active, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
appendFileSync(activeLogPath, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
} catch (error) {
fileFailed = true;
originalConsole.error('[logs] writing the launcher log failed:', error);
@@ -109,7 +109,7 @@ async function launch(job: LaunchJob): Promise<void> {
const plan = await planLaunch(job, record, settings);
if (plan === null) return;
const { lab, copyPath, stockPath, dataPath, port } = plan;
await buildForLaunch(job, record, plan, settings.autoSaveBackups);
await buildForLaunch(job, record, plan, settings);
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
if (signal.aborted) return;
@@ -187,10 +187,10 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
}
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, autoSaveBackups: boolean): Promise<void> {
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
const signal = job.stop.signal;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
if (autoSaveBackups) {
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
await saveBackup({ ...record, dataPath }, userId, 'launch');
@@ -209,6 +209,7 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
steamLibraryConfirmed,
...resourcePaths(),
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
hookLogging: settings.loggingEnabled,
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
}, signal, (filesWritten, filesTotal, file) => {
writtenFiles = filesWritten;
@@ -34,13 +34,17 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
}
export async function startLocalServer(
{ gameFolder, dataFolder, port }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
{ gameFolder, dataFolder, port, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
): Promise<LocalServer> {
signal.throwIfAborted();
const worker = utilityProcess.fork(join(import.meta.dirname, 'server-worker.js'), [gameFolder, dataFolder, String(port)], {
serviceName: 'WTOffline local server',
stdio: 'pipe',
});
const worker = utilityProcess.fork(
join(import.meta.dirname, 'server-worker.js'),
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'],
{
serviceName: 'WTOffline local server',
stdio: 'pipe',
},
);
forwardProcessOutput(worker.stdout, 'server', 'info');
forwardProcessOutput(worker.stderr, 'server', 'error');
@@ -49,7 +49,10 @@ export async function runOrdinaryLaunch(
const args = parseLaunchArguments(settings.launchArguments);
if (!args) throw new AppError('launch_game_failed');
publish('starting-server');
const server = await startLocalServer({ gameFolder: copyPath, dataFolder: dataPath, port }, signal);
const server = await startLocalServer(
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled },
signal,
);
const stop = new AbortController();
const runSignal = AbortSignal.any([signal, stop.signal]);
const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); });
@@ -10,6 +10,7 @@ export interface BuildRequest {
readonly patches: string;
readonly networkHookLibrary: string;
readonly decalCache?: string;
readonly hookLogging: boolean;
readonly acceptedUnavailable: readonly string[];
}
@@ -41,6 +41,7 @@ function build(request: BuildRequest): void {
port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
placeholderDecals: decalCache === undefined,
hookLogging: request.hookLogging,
});
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable);
@@ -3,13 +3,14 @@ import { startServer } from '@wto/server';
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
async function serve(): Promise<void> {
const [gameFolder, dataFolder, portText] = process.argv.slice(2);
const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2);
const port = Number(portText);
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Invalid local server arguments.');
}
const server = await startServer({ gameFolder, dataFolder, port, report: console.info });
console.info('Traffic log:', server.logFolder);
const loggingEnabled = loggingFlag !== '0';
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info });
if (server.logFolder) console.info('Traffic log:', server.logFolder);
process.parentPort.once('message', () => {
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
console.error('Could not close the local server:', error);
+15 -2
View File
@@ -149,13 +149,26 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
bar: home,
};
case 'about':
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} appUpdate={appUpdate} />, bar: home };
return {
side: homeSide,
main: (
<AboutPage
launcherVersion={info.version}
supportedVersions={supported}
patchPack={patchPack}
appUpdate={appUpdate}
loggingEnabled={settings.loggingEnabled}
onError={report}
/>
),
bar: home,
};
case 'settings': {
const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev');
const content = {
general: <GeneralSettings settings={settings} appUpdatesSupported={info.appUpdatesSupported} pictures={backgrounds.pictures} onError={report} />,
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
diag: <DiagnosticsSettings settings={settings} onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
dev: <DeveloperSettings settings={settings} onError={report} />,
};
return {
@@ -529,11 +529,15 @@
"reset": "Restore default"
},
"diagnostics": {
"recordLogs": "Record runtime logs",
"recordLogsToggle": "Write launcher, local server, and hook logs",
"recordLogsHint": "When disabled, stops writing launcher logs, local server traffic logs, and wto_ws.log (the game engine's own .game_logs are unaffected). Re-enable before exporting logs for troubleshooting.",
"loggingDisabledNotice": "Runtime logging is currently disabled; exported archives include only existing logs and configuration.",
"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",
"exportHint": "Save launcher, local server, and game logs, settings, and the installation record to a ZIP file (excludes saves)",
"save": "Export…",
"saved": "Diagnostics saved to {{path}}.",
"serverStatus": "Local server status",
@@ -571,6 +575,12 @@
"about": {
"launcher": "Launcher {{version}}",
"supported": "Supported game versions: {{versions}}",
"feedback": {
"title": "Feedback and logs",
"export": "Save all logs",
"exportHint": "Pack launcher, local server, and game logs into a ZIP file for issue reports (excludes saves).",
"exportButton": "Save log ZIP…"
},
"pack": {
"title": "Adaptation data",
"current": "In use",
@@ -529,11 +529,15 @@
"reset": "恢复默认"
},
"diagnostics": {
"recordLogs": "生成运行日志",
"recordLogsToggle": "记录启动器、本地服务器和钩子日志",
"recordLogsHint": "关闭后停止写入启动器日志、本地服务器流量日志和 wto_ws.log(不影响游戏引擎原生的 .game_logs)。导出日志排查问题前建议重新开启。",
"loggingDisabledNotice": "当前已关闭运行日志记录,导出的压缩包仅包含已有历史日志和配置。",
"logs": "日志",
"logsHint": "启动器运行日志",
"openLogs": "打开日志文件夹",
"export": "导出诊断信息",
"exportHint": "导出包含日志、设置和安装记录的 ZIP 文件",
"exportHint": "导出包含启动器、本地服务器与游戏日志、设置和安装记录的 ZIP 文件(不含存档)",
"save": "导出…",
"saved": "诊断信息已保存到 {{path}}。",
"serverStatus": "本地服务器状态页",
@@ -571,6 +575,12 @@
"about": {
"launcher": "启动器 {{version}}",
"supported": "支持的游戏版本:{{versions}}",
"feedback": {
"title": "问题反馈",
"export": "保存全部日志",
"exportHint": "打包启动器、本地服务器及游戏日志为 ZIP 文件以便反馈问题(不含存档)。",
"exportButton": "保存日志 ZIP…"
},
"pack": {
"title": "适配数据",
"current": "当前使用",
@@ -1,7 +1,9 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { AppUpdateSection } from './AppUpdateSection.tsx';
import type { PatchPackState } from '../../shell/usePatchPack.ts';
@@ -11,10 +13,12 @@ interface AboutPageProps {
readonly supportedVersions: readonly string[];
readonly patchPack: PatchPackState;
readonly appUpdate: AppUpdateState;
readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void;
}
/** The launcher's version, the game versions it supports, adaptation pack updates, and the project statement. */
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate }: AboutPageProps) {
/** The launcher's version, the game versions it supports, adaptation pack updates, log export, and the project statement. */
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate, loggingEnabled, onError }: AboutPageProps) {
const { t } = useTranslation();
return (
<Sheet title={t('nav.about')}>
@@ -28,12 +32,48 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
</div>
<AppUpdateSection state={appUpdate} />
<PatchPackSection state={patchPack} />
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3>
<p className="lead">{t('about.statementBody')}</p>
</Sheet>
);
}
function FeedbackLogsSection({ loggingEnabled, onError }: {
readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void;
}) {
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 (
<>
<h3 className="section-title section-title-spaced">{t('about.feedback.title')}</h3>
<Row label={t('about.feedback.export')} hint={t('about.feedback.exportHint')}>
<button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}>
{t('about.feedback.exportButton')}
</button>
</Row>
{!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</>
);
}
function PatchPackSection({ state }: { readonly state: PatchPackState }) {
const { t } = useTranslation();
const { active, check, busy } = state;
@@ -1,19 +1,25 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { Settings } from '@shared/schemas/settings.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
interface DiagnosticsSettingsProps {
readonly settings: Settings;
readonly serverRunning: boolean;
readonly onError: (error: unknown) => void;
}
export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSettingsProps) {
export function DiagnosticsSettings({ settings, onError, serverRunning }: DiagnosticsSettingsProps) {
const { t } = useTranslation();
const [exporting, setExporting] = useState(false);
const [savedPath, setSavedPath] = useState<string | null>(null);
const updateLogging = (loggingEnabled: boolean): void => {
ipcInvoke('settings:update', { loggingEnabled }).catch(onError);
};
async function save(): Promise<void> {
setExporting(true);
setSavedPath(null);
@@ -29,6 +35,16 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti
return (
<Sheet title={t('settings.sections.diag')}>
<Row label={t('settings.diagnostics.recordLogs')} hint={t('settings.diagnostics.recordLogsHint')}>
<label className="check check-inline">
<input
type="checkbox"
checked={settings.loggingEnabled}
onChange={(event) => updateLogging(event.target.checked)}
/>
{t('settings.diagnostics.recordLogsToggle')}
</label>
</Row>
<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')}
@@ -44,6 +60,7 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti
{t('settings.diagnostics.openStatus')}
</button>
</Row>
{!settings.loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</Sheet>
);
@@ -28,6 +28,8 @@ export const SettingsSchema = z.object({
windowClose: WindowCloseSchema.default('quit'),
afterGameStarts: AfterGameStartsSchema.default('minimize'),
autoSaveBackups: z.boolean().default(true),
/** Write launcher, local server traffic, and wto_ws.log files; does not affect game .game_logs. */
loggingEnabled: z.boolean().default(true),
launchPortMode: PortModeSchema.default('auto'),
launchPort: PortSchema.default(27015),
closeServerOnGameExit: z.boolean().default(true),
@@ -50,6 +52,7 @@ export const SettingsPatchSchema = z.object({
windowClose: WindowCloseSchema.optional(),
afterGameStarts: AfterGameStartsSchema.optional(),
autoSaveBackups: z.boolean().optional(),
loggingEnabled: z.boolean().optional(),
launchPortMode: PortModeSchema.optional(),
launchPort: PortSchema.optional(),
closeServerOnGameExit: z.boolean().optional(),
+3 -1
View File
@@ -69,6 +69,8 @@ export interface ServerOptions {
readonly port: number;
/** Start-up progress lines (static data extraction, game modes). */
readonly report?: (line: string) => void;
/** Whether to write traffic logs under `<dataFolder>/logs`; defaults to true. */
readonly loggingEnabled?: boolean;
}
export const LOOPBACK = '127.0.0.1';
@@ -143,7 +145,7 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
})),
new DownloadableContentService(),
]);
const log = new TrafficLog(options.dataFolder);
const log = new TrafficLog(options.dataFolder, options.loggingEnabled ?? true);
const listener = createPortListener(
router,
matchingRequests({
+11 -2
View File
@@ -20,11 +20,19 @@ export interface MatchingLogEntry {
export class TrafficLog {
readonly folder: string;
readonly #enabled: boolean;
readonly #linesPath: string;
readonly #bodiesFolder: string;
#sequence = 0;
constructor(dataFolder: string) {
constructor(dataFolder: string, enabled = true) {
this.#enabled = enabled;
if (!enabled) {
this.folder = '';
this.#linesPath = '';
this.#bodiesFolder = '';
return;
}
this.folder = join(dataFolder, 'logs', new Date().toISOString().replace(/[:.]/g, '-'));
this.#linesPath = join(this.folder, 'requests.jsonl');
this.#bodiesFolder = join(this.folder, 'bodies');
@@ -96,11 +104,12 @@ export class TrafficLog {
}
#append(line: object): void {
if (!this.#enabled) return;
appendFileSync(this.#linesPath, JSON.stringify(line) + '\n');
}
#writeBody(id: number, suffix: string, content: Uint8Array | string | undefined): string | null {
if (content === undefined || byteLength(content) === 0) return null;
if (!this.#enabled || content === undefined || byteLength(content) === 0) return null;
const name = `${String(id).padStart(6, '0')}.${suffix}`;
writeFileSync(join(this.#bodiesFolder, name), content);
return name;
+5 -1
View File
@@ -4,6 +4,7 @@
* wto_ws.cfg, written by the build into the game copy (@wto/patcher network-hook.ts):
* port=<local server port> without a valid port the hooks still answer every host name
* locally but refuse every connection that would leave the machine
* log=0|1 optional, defaults to 1; when 0, wto_ws.log is not opened
* exe.time_date_stamp=0x... the executable the native values were resolved for
* exe.size_of_image=0x...
* native.<name>=<value> what the LocalMP modules need from the executable: RVAs of
@@ -33,6 +34,7 @@ typedef struct NativeValue {
static wchar_t g_folder[MAX_PATH];
static CRITICAL_SECTION g_log_lock;
static FILE *g_log;
static int g_log_enabled = 1;
static NativeValue g_native[NATIVE_VALUES_MAX];
static size_t g_native_count;
static int64_t g_exe_time_date_stamp = -1;
@@ -98,6 +100,8 @@ static void read_settings(void)
line[strcspn(line, "\r\n")] = '\0';
if (strncmp(line, "port=", 5) == 0)
read_port(line + 5);
else if (strncmp(line, "log=", 4) == 0)
g_log_enabled = atoi(line + 4) != 0;
else if (strncmp(line, "exe.time_date_stamp=", 20) == 0)
parse_value(line + 20, &g_exe_time_date_stamp);
else if (strncmp(line, "exe.size_of_image=", 18) == 0)
@@ -140,7 +144,7 @@ void config_load(HMODULE self)
InitializeCriticalSection(&g_log_lock);
find_folder(self);
read_settings();
if (_snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.log", g_folder) >= 0)
if (g_log_enabled && _snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.log", g_folder) >= 0)
g_log = _wfsopen(path, L"w", _SH_DENYWR);
log_line("wto_ws: local server port %u%s", g_service_port, g_service_port ? "" : " (none: outside connections are refused)");
log_line("wto_ws: %u native value(s) for the LocalMP modules", (unsigned)g_native_count);
+5 -1
View File
@@ -44,6 +44,8 @@ export interface GameCopyInputs {
readonly multiVehiclePackIds: readonly string[];
/** Store the placeholder decal index; false when the player's own web cache is copied. */
readonly placeholderDecals: boolean;
/** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */
readonly hookLogging?: boolean;
}
/** One file of the game copy, by its path relative to the copy folder. */
@@ -96,7 +98,9 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
const mainPack = rebuildMainPack(inputs.stock.mainPack, endpoint, bundles);
const executableFolder = dirname(GAME_FILES.executable);
const hookSettings = networkHookSettings(endpoint, stockImage, native.values);
const hookSettings = networkHookSettings(endpoint, stockImage, native.values, {
loggingEnabled: inputs.hookLogging ?? true,
});
const files: GameCopyFile[] = [
{ path: GAME_FILES.charPack, content: charPack },
{ path: GAME_FILES.mainPack, content: mainPack.pack },
+6 -1
View File
@@ -17,7 +17,12 @@ export function networkHookSettings(
endpoint: LocalEndpoint,
stock: PeImage,
nativeValues: ReadonlyMap<string, number>,
options?: { readonly loggingEnabled?: boolean },
): { name: string; content: Uint8Array } {
const lines = [`port=${endpoint.port}`, ...nativeSettingsLines(stock, nativeValues)];
const lines = [
`port=${endpoint.port}`,
...(options?.loggingEnabled === false ? ['log=0'] : []),
...nativeSettingsLines(stock, nativeValues),
];
return { name: SETTINGS, content: new TextEncoder().encode(`${lines.join('\n')}\n`) };
}