From 85e1c27274e2f1e77835ca1c82d8d8a31c313a18 Mon Sep 17 00:00:00 2001 From: pompurin404 Date: Thu, 1 Aug 2024 13:16:57 +0800 Subject: [PATCH] setup logs --- src/main/dirs.ts | 13 ++++++++ src/main/manager.ts | 30 +++++++++++++++---- .../components/sider/mihomo-core-card.tsx.tsx | 5 +++- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/src/main/dirs.ts b/src/main/dirs.ts index 5e845a4..79fd485 100644 --- a/src/main/dirs.ts +++ b/src/main/dirs.ts @@ -15,6 +15,9 @@ export function initDirs(): void { if (!fs.existsSync(mihomoWorkDir())) { fs.mkdirSync(mihomoWorkDir()) } + if (!fs.existsSync(logDir())) { + fs.mkdirSync(logDir()) + } } export function mihomoCoreDir(): string { @@ -57,3 +60,13 @@ export function mihomoWorkDir(): string { export function mihomoWorkConfigPath(): string { return path.join(mihomoWorkDir(), 'config.yaml') } + +export function logDir(): string { + return path.join(dataDir, 'logs') +} + +export function logPath(): string { + const date = new Date() + const name = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}` + return path.join(logDir(), `${name}.log`) +} diff --git a/src/main/manager.ts b/src/main/manager.ts index 837853e..7bc3760 100644 --- a/src/main/manager.ts +++ b/src/main/manager.ts @@ -1,15 +1,35 @@ -import { execFile, ChildProcess } from 'child_process' -import { mihomoCorePath, mihomoWorkDir } from './dirs' +import { ChildProcess, execSync, spawn } from 'child_process' +import { logPath, mihomoCorePath, mihomoWorkDir } from './dirs' import { generateProfile } from './factory' import { appConfig } from './config' - +import fs from 'fs' let child: ChildProcess -export function startCore(): void { +export async function startCore(): Promise { const corePath = mihomoCorePath(appConfig.core ?? 'mihomo') generateProfile() stopCore() - child = execFile(corePath, ['-d', mihomoWorkDir()], () => {}) + if (process.platform !== 'win32') { + execSync(`chmod +x ${corePath}`) + } + child = spawn(corePath, ['-d', mihomoWorkDir()]) + child.stdout?.on('data', (data) => { + fs.writeFileSync( + logPath(), + data + .toString() + .split('\n') + .map((line: string) => { + if (line) return `[Mihomo]: ${line}` + return '' + }) + .filter(Boolean) + .join('\n'), + { + flag: 'a' + } + ) + }) } export function stopCore(): void { diff --git a/src/renderer/src/components/sider/mihomo-core-card.tsx.tsx b/src/renderer/src/components/sider/mihomo-core-card.tsx.tsx index e6b472c..5399510 100644 --- a/src/renderer/src/components/sider/mihomo-core-card.tsx.tsx +++ b/src/renderer/src/components/sider/mihomo-core-card.tsx.tsx @@ -62,7 +62,10 @@ const MihomoCoreCard: React.FC = () => { onAction={async (key) => { await patchAppConfig({ core: key as 'mihomo' | 'mihomo-alpha' }) await restartCore() - await mutate() + mutate() + setTimeout(() => { + mutate() + }, 200) }} > {CoreMap['mihomo']}