🔊 优化日志

This commit is contained in:
刘嘉伟 2024-08-06 00:17:39 +08:00
parent 29194f1010
commit cc0d8750a2
8 changed files with 47 additions and 33 deletions

View File

@ -165,11 +165,9 @@ export const generateConfig = (
) => { ) => {
listProxy((err3, proxys) => { listProxy((err3, proxys) => {
if (!err3) { if (!err3) {
console.log(config, 'config')
const {currentVersion} = config; const {currentVersion} = config;
let filename = null; let filename = null;
let configContent = ""; let configContent = "";
console.log(currentVersion, "currentVersion")
if (currentVersion < 124395282) { if (currentVersion < 124395282) {
// 版本小于v0.52.0 // 版本小于v0.52.0
filename = "frp.ini"; filename = "frp.ini";
@ -179,7 +177,7 @@ export const generateConfig = (
configContent = genTomlConfig(config, proxys) configContent = genTomlConfig(config, proxys)
} }
const configPath = path.join(app.getPath("userData"), filename) const configPath = path.join(app.getPath("userData"), filename)
console.debug("生成配置成功", configPath) log.info(`生成配置成功 配置路径:${configPath}`)
fs.writeFile( fs.writeFile(
configPath, // 配置文件目录 configPath, // 配置文件目录
configContent, // 配置文件内容 configContent, // 配置文件内容
@ -219,8 +217,8 @@ const startFrpcProcess = (commandPath: string, configPath: string) => {
}); });
frpcStatusListener = setInterval(() => { frpcStatusListener = setInterval(() => {
const status = frpcProcessStatus() const status = frpcProcessStatus()
log.debug(`监听frpc子进程状态${status}`)
if (!status) { if (!status) {
log.info("连接已断开")
new Notification({ new Notification({
title: "Frpc Desktop", title: "Frpc Desktop",
body: "连接已断开,请前往日志查看原因" body: "连接已断开,请前往日志查看原因"
@ -240,7 +238,7 @@ export const reloadFrpcProcess = () => {
if (config) { if (config) {
generateConfig(config, configPath => { generateConfig(config, configPath => {
const command = `${runningCmd.commandPath} reload -c ${configPath}`; const command = `${runningCmd.commandPath} reload -c ${configPath}`;
log.info(`${command}`) log.info(`载配置${command}`)
exec(command, { exec(command, {
cwd: app.getPath("userData"), cwd: app.getPath("userData"),
shell: true shell: true
@ -259,9 +257,9 @@ export const stopFrpcProcess = (callback?: () => void) => {
if (frpcProcess) { if (frpcProcess) {
treeKill(frpcProcess.pid, (error: Error) => { treeKill(frpcProcess.pid, (error: Error) => {
if (error) { if (error) {
console.log("关闭失败", frpcProcess.pid, error) log.error(`关闭frpc子进程失败 pid${frpcProcess.pid} error${error}`)
} else { } else {
console.log('关闭成功') log.info(`关闭frpc子进程成功`)
frpcProcess = null frpcProcess = null
clearInterval(frpcStatusListener) clearInterval(frpcStatusListener)
} }
@ -295,7 +293,6 @@ export const startFrpWorkerProcess = async (config: Config) => {
getFrpcVersionWorkerPath( getFrpcVersionWorkerPath(
config.currentVersion, config.currentVersion,
(frpcVersionPath: string) => { (frpcVersionPath: string) => {
console.log(1, '1')
if (frpcVersionPath) { if (frpcVersionPath) {
generateConfig(config, configPath => { generateConfig(config, configPath => {
const platform = process.platform; const platform = process.platform;
@ -340,6 +337,7 @@ export const initFrpcApi = () => {
ipcMain.on("frpc.stop", () => { ipcMain.on("frpc.stop", () => {
if (frpcProcess && !frpcProcess.killed) { if (frpcProcess && !frpcProcess.killed) {
stopFrpcProcess(() => { stopFrpcProcess(() => {
}) })
} }
}); });

View File

@ -7,7 +7,7 @@ const zlib = require("zlib");
const {download} = require("electron-dl"); const {download} = require("electron-dl");
const unzipper = require('unzipper'); const unzipper = require('unzipper');
const AdmZip = require('adm-zip'); const AdmZip = require('adm-zip');
const log = require('electron-log');
const versionRelation = { const versionRelation = {
"win32_x64": ["window", "amd64"], "win32_x64": ["window", "amd64"],
@ -21,6 +21,7 @@ const versionRelation = {
const unTarGZ = (tarGzPath: string, targetPath: string) => { const unTarGZ = (tarGzPath: string, targetPath: string) => {
const tar = require("tar"); const tar = require("tar");
const unzip = zlib.createGunzip(); const unzip = zlib.createGunzip();
log.debug(`开始解压tar.gz${tarGzPath} 目标目录:${targetPath}`);
const readStream = fs.createReadStream(tarGzPath); const readStream = fs.createReadStream(tarGzPath);
if (!fs.existsSync(unzip)) { if (!fs.existsSync(unzip)) {
fs.mkdirSync(targetPath, {recursive: true}); fs.mkdirSync(targetPath, {recursive: true});
@ -31,7 +32,9 @@ const unTarGZ = (tarGzPath: string, targetPath: string) => {
filter: filePath => path.basename(filePath) === "frpc" filter: filePath => path.basename(filePath) === "frpc"
}) })
); );
return path.join("frp", path.basename(tarGzPath, ".tar.gz")); const frpcPath = path.join("frp", path.basename(tarGzPath, ".tar.gz"));
log.debug(`解压完成 解压后目录:${frpcPath}`);
return frpcPath;
// .on("finish", () => { // .on("finish", () => {
// console.log("解压完成!"); // console.log("解压完成!");
// }); // });
@ -41,24 +44,27 @@ const unZip = (zipPath: string, targetPath: string) => {
if (!fs.existsSync(path.join(targetPath, path.basename(zipPath, ".zip")))) { if (!fs.existsSync(path.join(targetPath, path.basename(zipPath, ".zip")))) {
fs.mkdirSync(path.join(targetPath, path.basename(zipPath, ".zip")), {recursive: true}); fs.mkdirSync(path.join(targetPath, path.basename(zipPath, ".zip")), {recursive: true});
} }
log.debug(`开始解压zip${zipPath} 目标目录:${targetPath}`);
/** /**
* unzipper解压 * unzipper解压
*/ */
// fs.createReadStream(zipPath) // fs.createReadStream(zipPath)
// .pipe(unzipper.Extract({ path: targetPath })) // .pipe(unzipper.Extract({ path: targetPath }))
// // 只解压frpc.exe // // 只解压frpc.exe
// // .pipe(unzipper.ParseOne('frpc')) // // .pipe(unzipper.ParseOne('frpc'))
// // .pipe(fs.createWriteStream(path.join(targetPath, path.basename(zipPath, ".zip"), "frpc.exe"))) // // .pipe(fs.createWriteStream(path.join(targetPath, path.basename(zipPath, ".zip"), "frpc.exe")))
// .on('finish', () => { // .on('finish', () => {
// console.log('File extracted successfully.'); // console.log('File extracted successfully.');
// }) // })
// .on('error', (err) => { // .on('error', (err) => {
// console.error('Error extracting file:', err); // console.error('Error extracting file:', err);
// }); // });
const zip = new AdmZip(zipPath) const zip = new AdmZip(zipPath)
zip.extractAllTo(targetPath, true); // 第二个参数为 true表示覆盖已存在的文件 zip.extractAllTo(targetPath, true); // 第二个参数为 true表示覆盖已存在的文件
return path.join("frp", path.basename(zipPath, ".zip")) const frpcPath = path.join("frp", path.basename(zipPath, ".zip"));
log.debug(`解压完成 解压后目录:${frpcPath}`);
return frpcPath
} }
export const initGitHubApi = () => { export const initGitHubApi = () => {
@ -73,7 +79,6 @@ export const initGitHubApi = () => {
const {assets} = getVersion(versionId); const {assets} = getVersion(versionId);
const arch = process.arch; const arch = process.arch;
const platform = process.platform; const platform = process.platform;
console.log(platform + '_' +arch)
const asset = assets.find( const asset = assets.find(
f => { f => {
const a = versionRelation[`${platform}_${arch}`] const a = versionRelation[`${platform}_${arch}`]
@ -85,7 +90,7 @@ export const initGitHubApi = () => {
} }
); );
if (asset) { if (asset) {
console.log(asset.name) log.info(`找到对应版本 ${asset.name}`)
} }
return asset; return asset;
}; };
@ -119,6 +124,7 @@ export const initGitHubApi = () => {
} }
return m; return m;
}); });
log.debug(`获取到frp版本${JSON.stringify(returnVersionsData)}`)
event.reply("Download.frpVersionHook", returnVersionsData); event.reply("Download.frpVersionHook", returnVersionsData);
}); });
}); });
@ -131,6 +137,7 @@ export const initGitHubApi = () => {
ipcMain.on("github.download", async (event, args) => { ipcMain.on("github.download", async (event, args) => {
const version = getVersion(args); const version = getVersion(args);
const asset = getAdaptiveAsset(args); const asset = getAdaptiveAsset(args);
log.info(`开始下载frp version${version} asset${asset}`)
const {browser_download_url} = asset; const {browser_download_url} = asset;
// 数据目录 // 数据目录
await download(BrowserWindow.getFocusedWindow(), browser_download_url, { await download(BrowserWindow.getFocusedWindow(), browser_download_url, {
@ -143,6 +150,7 @@ export const initGitHubApi = () => {
}); });
}, },
onCompleted: () => { onCompleted: () => {
log.info(`frp下载完成 version${version} asset${asset}`)
const targetPath = path.resolve(path.join(app.getPath("userData"), "frp")); const targetPath = path.resolve(path.join(app.getPath("userData"), "frp"));
const ext = path.extname(asset.name) const ext = path.extname(asset.name)
let frpcVersionPath = "" let frpcVersionPath = ""
@ -152,7 +160,6 @@ export const initGitHubApi = () => {
`${asset.name}` `${asset.name}`
), ),
targetPath) targetPath)
console.log(frpcVersionPath, '1')
} else if (ext === '.gz' && asset.name.includes(".tar.gz")) { } else if (ext === '.gz' && asset.name.includes(".tar.gz")) {
frpcVersionPath = unTarGZ( frpcVersionPath = unTarGZ(
path.join( path.join(
@ -179,7 +186,6 @@ export const initGitHubApi = () => {
*/ */
ipcMain.on("github.deleteVersion", async (event, args) => { ipcMain.on("github.deleteVersion", async (event, args) => {
const {absPath, id} = args; const {absPath, id} = args;
console.log('删除下载', args)
if (fs.existsSync(absPath)) { if (fs.existsSync(absPath)) {
deleteVersionById(id, () => { deleteVersionById(id, () => {
fs.unlinkSync(absPath) fs.unlinkSync(absPath)

View File

@ -18,6 +18,7 @@ export const initLoggerApi = () => {
event.reply("Logger.getLog.hook", content); event.reply("Logger.getLog.hook", content);
}); });
}); });
ipcMain.on("logger.update", (event, args) => { ipcMain.on("logger.update", (event, args) => {
fs.watch(logPath, (eventType, filename) => { fs.watch(logPath, (eventType, filename) => {
if (eventType === "change") { if (eventType === "change") {

View File

@ -8,6 +8,7 @@ import {initFrpcApi, startFrpWorkerProcess, stopFrpcProcess} from "../api/frpc";
import {initLoggerApi} from "../api/logger"; import {initLoggerApi} from "../api/logger";
import {initFileApi} from "../api/file"; import {initFileApi} from "../api/file";
import {getConfig} from "../storage/config"; import {getConfig} from "../storage/config";
import log from "electron-log";
// The built directory structure // The built directory structure
// //
// ├─┬ dist-electron // ├─┬ dist-electron
@ -47,6 +48,8 @@ const preload = join(__dirname, "../preload/index.js");
const url = process.env.VITE_DEV_SERVER_URL; const url = process.env.VITE_DEV_SERVER_URL;
const indexHtml = join(process.env.DIST, "index.html"); const indexHtml = join(process.env.DIST, "index.html");
let isQuiting; let isQuiting;
log.transports.file.level = 'debug';
log.transports.console.level = "debug";
async function createWindow() { async function createWindow() {
win = new BrowserWindow({ win = new BrowserWindow({
@ -114,6 +117,7 @@ async function createWindow() {
} }
export const createTray = () => { export const createTray = () => {
log.info(`当前环境 platform${process.platform} arch${process.arch}`)
let menu: Array<(MenuItemConstructorOptions) | (MenuItem)> = [ let menu: Array<(MenuItemConstructorOptions) | (MenuItem)> = [
{ {
label: '显示主窗口', click: function () { label: '显示主窗口', click: function () {
@ -147,6 +151,7 @@ export const createTray = () => {
if (!err) { if (!err) {
if (config) { if (config) {
if (config.systemStartupConnect) { if (config.systemStartupConnect) {
log.info(`已开启自动连接 正在自动连接服务器`)
startFrpWorkerProcess(config) startFrpWorkerProcess(config)
} }
} }
@ -187,6 +192,7 @@ app.on("activate", () => {
}); });
app.on('before-quit', () => { app.on('before-quit', () => {
log.info("退出")
isQuiting = true; isQuiting = true;
}) })
@ -208,8 +214,7 @@ ipcMain.handle("open-win", (_, arg) => {
}); });
ipcMain.on('open-url', (event, url) => { ipcMain.on('open-url', (event, url) => {
shell.openExternal(url).then(r => { shell.openExternal(url).then(r => {});
});
}); });
initGitHubApi(); initGitHubApi();

View File

@ -38,7 +38,7 @@ export const saveConfig = (
cb?: (err: Error | null, numberOfUpdated: number, upsert: boolean) => void cb?: (err: Error | null, numberOfUpdated: number, upsert: boolean) => void
) => { ) => {
document["_id"] = "1"; document["_id"] = "1";
log.debug("保存日志", document) log.debug(`保存日志 ${JSON.stringify(document)}`)
configDB.update({_id: "1"}, document, {upsert: true}, cb); configDB.update({_id: "1"}, document, {upsert: true}, cb);
}; };

View File

@ -1,6 +1,7 @@
import Datastore from "nedb"; import Datastore from "nedb";
import path from "path"; import path from "path";
import { app } from "electron"; import { app } from "electron";
const log = require('electron-log');
const proxyDB = new Datastore({ const proxyDB = new Datastore({
autoload: true, autoload: true,
@ -25,7 +26,7 @@ export const insertProxy = (
proxy: Proxy, proxy: Proxy,
cb?: (err: Error | null, document: Proxy) => void cb?: (err: Error | null, document: Proxy) => void
) => { ) => {
console.log("新增", proxy); log.debug(`新增代理:${JSON.stringify(proxy)}`);
proxyDB.insert(proxy, cb); proxyDB.insert(proxy, cb);
}; };
@ -38,6 +39,7 @@ export const deleteProxyById = (
_id: string, _id: string,
cb?: (err: Error | null, n: number) => void cb?: (err: Error | null, n: number) => void
) => { ) => {
log.debug(`删除代理:${_id}`);
proxyDB.remove({ _id: _id }, cb); proxyDB.remove({ _id: _id }, cb);
}; };
@ -48,6 +50,7 @@ export const updateProxyById = (
proxy: Proxy, proxy: Proxy,
cb?: (err: Error | null, numberOfUpdated: number, upsert: boolean) => void cb?: (err: Error | null, numberOfUpdated: number, upsert: boolean) => void
) => { ) => {
log.debug(`修改代理:${proxy}`);
proxyDB.update({ _id: proxy._id }, proxy, {}, cb); proxyDB.update({ _id: proxy._id }, proxy, {}, cb);
}; };

View File

@ -1,7 +1,7 @@
import Datastore from "nedb"; import Datastore from "nedb";
import path from "path"; import path from "path";
import {Proxy} from "./proxy";
import {app} from "electron"; import {app} from "electron";
const log = require('electron-log');
const versionDB = new Datastore({ const versionDB = new Datastore({
autoload: true, autoload: true,
@ -17,6 +17,7 @@ export const insertVersion = (
version: any, version: any,
cb?: (err: Error | null, document: any) => void cb?: (err: Error | null, document: any) => void
) => { ) => {
log.debug(`新增版本:${JSON.stringify(version)}`);
versionDB.insert(version, cb); versionDB.insert(version, cb);
}; };
@ -38,5 +39,6 @@ export const getVersionById = (
}; };
export const deleteVersionById = (id: string, callback: (err: Error | null, document: any) => void) => { export const deleteVersionById = (id: string, callback: (err: Error | null, document: any) => void) => {
log.debug(`删除版本:${id}`);
versionDB.remove({id: id}, callback); versionDB.remove({id: id}, callback);
} }

View File

@ -49,7 +49,6 @@ onMounted(() => {
onUnmounted(() => { onUnmounted(() => {
ipcRenderer.removeAllListeners("Logger.getLog.hook"); ipcRenderer.removeAllListeners("Logger.getLog.hook");
ipcRenderer.removeAllListeners("Logger.update.hook");
}); });
</script> </script>
<template> <template>