示例工程 06-dev-debug-logging
06-dev-debug-logging/app/main/index.ts
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import path from "node:path";
import {
CH,
isLogLevel,
type DebugInfo,
type LogLevel,
type LogRecord,
} from "../shared/ipc";
const isSmoke =
process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const LOG_LIMIT = 64 * 1024;
let mainWindow: BrowserWindow | null = null;
let started = false;
const logs: LogRecord[] = [];
let logFile = "";
let logSize = 0;
function rotateLog(): void {
if (!logFile) return;
try {
fsSync.renameSync(logFile, `${logFile}.1`);
} catch {
// 第一次轮转时旧文件可能不存在。
}
try {
fsSync.writeFileSync(logFile, "");
} catch {
// 磁盘满或权限问题时,日志失败不应拖垮应用。
}
logSize = 0;
}
function log(level: LogLevel, evt: string, msg?: string): void {
const record: LogRecord = {
at: Date.now(),
level,
evt,
...(msg ? { msg } : {}),
};
logs.push(record);
if (logs.length > 100) logs.shift();
const line = JSON.stringify(record);
process.stdout.write(`${line}\n`);
if (!logFile) return;
try {
fsSync.appendFileSync(logFile, `${line}\n`);
logSize += Buffer.byteLength(line) + 1;
if (logSize >= LOG_LIMIT) rotateLog();
} catch (error) {
process.stderr.write(`log write failed: ${String(error)}\n`);
}
}
function logFileSize(): number {
try {
return fsSync.statSync(logFile).size;
} catch {
return 0;
}
}
function collectInfo(): DebugInfo {
return {
logs: logs.slice(-30),
logFile,
logSize: logFileSize(),
logLimit: LOG_LIMIT,
devToolsOpen: mainWindow?.webContents.isDevToolsOpened() ?? false,
enableLogging: process.env.ELECTRON_ENABLE_LOGGING === "1",
execArgv: process.execArgv,
isPackaged: app.isPackaged,
};
}
function resolvePreload(): string {
const candidates = [
path.join(__dirname, "preload.cjs"),
path.join(__dirname, "../preload/index.cjs"),
path.join(__dirname, "preload.js"),
];
return (
candidates.find((candidate) => fsSync.existsSync(candidate)) ??
candidates[0] ??
""
);
}
function createWindow(): void {
mainWindow = new BrowserWindow({
width: 1000,
height: 720,
show: false,
backgroundColor: "#ffffff",
webPreferences: {
preload: resolvePreload(),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: true,
},
});
mainWindow.once("ready-to-show", () => {
mainWindow?.show();
});
mainWindow.webContents.on("did-finish-load", () => {
if (started) return;
started = true;
const pid = mainWindow?.webContents.getOSProcessId() ?? -1;
log("info", "window-created", String(pid));
if (isSmoke) {
void runSmoke();
} else if (isShots) {
void runShots();
}
});
mainWindow.on("closed", () => {
if (!isSmoke) log("info", "window-closed");
mainWindow = null;
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
void mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
} else {
void mainWindow.loadFile(
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
);
}
}
async function runSmoke(): Promise<void> {
try {
log("info", "smoke-start");
log("warn", "smoke-sample", "示例消息");
await new Promise((resolve) => setTimeout(resolve, 100));
const info = collectInfo();
process.stdout.write(
`${JSON.stringify({
evt: "smoke",
ok: info.logs.length >= 2 && info.logFile.endsWith("main.log"),
logs: info.logs.length,
logFile: info.logFile,
logSize: info.logSize,
enableLogging: info.enableLogging,
})}\n`,
);
app.quit();
} catch (error) {
process.stdout.write(
`${JSON.stringify({ evt: "error", message: String(error) })}\n`,
);
app.exit(1);
}
}
async function runShots(): Promise<void> {
try {
const dir = path.resolve(
process.cwd(),
"../../../docs/assets/images/06-dev-debug-logging",
);
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
await mainWindow?.webContents.executeJavaScript(
`new Promise((resolve) => {
const started = Date.now();
const tick = () => {
if (typeof window.__setTab === "function") resolve(true);
else if (Date.now() - started > 3000) resolve(false);
else setTimeout(tick, 20);
};
tick();
})`,
);
const shots = [
{ tab: "stream", file: "06-01-stream.png" },
{ tab: "file", file: "06-02-file.png" },
{ tab: "debug", file: "06-03-debug.png" },
];
for (const shot of shots) {
await mainWindow?.webContents.executeJavaScript(
`window.__setTab(${JSON.stringify(shot.tab)})`,
);
await new Promise((resolve) => setTimeout(resolve, 120));
const image = await mainWindow?.webContents.capturePage();
if (!image) throw new Error("capturePage returned null");
const png = image.toPNG();
fsSync.writeFileSync(path.join(dir, shot.file), png);
fsSync.writeFileSync(path.join(dir, "raw", shot.file), png);
log("debug", "shot", shot.file);
}
app.quit();
} catch (error) {
process.stdout.write(
`${JSON.stringify({ evt: "error", message: String(error) })}\n`,
);
app.exit(1);
}
}
ipcMain.handle(CH.info, () => collectInfo());
ipcMain.handle(CH.log, (_event, level: unknown, msg: unknown) => {
if (!isLogLevel(level) || typeof msg !== "string" || msg.length > 500) {
return { ok: false };
}
log(level, "renderer-log", msg);
return { ok: true };
});
ipcMain.handle(CH.clear, () => {
logs.length = 0;
if (logFile) {
try {
fsSync.writeFileSync(logFile, "");
} catch {
// 清空失败仍返回成功,避免 UI 卡住。
}
}
logSize = 0;
return { ok: true };
});
ipcMain.handle(CH.devtools, () => {
mainWindow?.webContents.toggleDevTools();
return { ok: Boolean(mainWindow) };
});
app.whenReady().then(() => {
logFile = path.join(app.getPath("logs"), "main.log");
fsSync.mkdirSync(path.dirname(logFile), { recursive: true });
log("info", "app-ready");
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});