From ffb42bd131762a18ee8151f1325dc2556c64a8a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=98=89=E4=BC=9F?= <8473136@qq.com> Date: Wed, 8 Jan 2025 14:17:05 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=8A=20Refactor=20logging=20across=20mu?= =?UTF-8?q?ltiple=20modules:=20Updated=20logging=20statements=20to=20utili?= =?UTF-8?q?ze=20a=20new=20structured=20logging=20utility=20for=20improved?= =?UTF-8?q?=20traceability=20and=20consistency.=20Enhanced=20error=20handl?= =?UTF-8?q?ing=20and=20added=20informative=20logs=20for=20database=20opera?= =?UTF-8?q?tions,=20configuration=20management,=20and=20proxy=20handling.?= =?UTF-8?q?=20Masked=20sensitive=20data=20in=20logs=20to=20improve=20secur?= =?UTF-8?q?ity=20during=20configuration=20operations.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- electron/api/config.ts | 10 ++- electron/api/github.ts | 1 - electron/api/logger.ts | 20 ++--- electron/storage/config.ts | 68 +++++++++++++++-- electron/storage/proxy.ts | 143 +++++++++++++++++++++++++----------- electron/storage/version.ts | 58 ++++++++++++--- electron/utils/log.ts | 3 +- 7 files changed, 227 insertions(+), 76 deletions(-) diff --git a/electron/api/config.ts b/electron/api/config.ts index e4b5ccf..22b0130 100644 --- a/electron/api/config.ts +++ b/electron/api/config.ts @@ -7,7 +7,6 @@ import path from "path"; import fs from "fs"; import { logDebug, logError, logInfo, LogModule, logWarn } from "../utils/log"; -const log = require("electron-log"); const toml = require("@iarna/toml"); const { v4: uuidv4 } = require("uuid"); @@ -83,7 +82,9 @@ export const initConfigApi = win => { logWarn(LogModule.APP, "Export canceled by user."); return; } - log.info( + + logInfo( + LogModule.APP, `Exporting configuration to directory ${outputDirectory} with type: ${args}` ); getConfig((err1, config) => { @@ -279,7 +280,10 @@ export const initConfigApi = win => { } else { const filePath = result.filePaths[0]; const fileExtension = path.extname(filePath); // 获取文件后缀名 - log.info(`Importing file ${filePath} with extension ${fileExtension}`); + logWarn( + LogModule.APP, + `Importing file ${filePath} with extension ${fileExtension}` + ); if (fileExtension === ".toml") { parseTomlConfig(filePath); event.reply("Config.importConfig.hook", { diff --git a/electron/api/github.ts b/electron/api/github.ts index 8c43465..329bcf9 100644 --- a/electron/api/github.ts +++ b/electron/api/github.ts @@ -344,7 +344,6 @@ export const initGitHubApi = () => { ); }, onCompleted: () => { - log.info(`frp下载完成 url:${url} asset:${asset.name}`); logInfo( LogModule.GITHUB, `Download completed for versionId: ${versionId}, asset: ${asset.name}` diff --git a/electron/api/logger.ts b/electron/api/logger.ts index b350a15..7107ecb 100644 --- a/electron/api/logger.ts +++ b/electron/api/logger.ts @@ -9,43 +9,43 @@ export const initLoggerApi = () => { const readLogger = (callback: (content: string) => void) => { fs.readFile(logPath, "utf-8", (error, data) => { if (!error) { - logInfo(LogModule.LOGGER, "Log file read successfully."); + logInfo(LogModule.APP, "Log file read successfully."); callback(data); } else { - logError(LogModule.LOGGER, `Error reading log file: ${error.message}`); + logError(LogModule.APP, `Error reading log file: ${error.message}`); } }); }; ipcMain.on("logger.getLog", async (event, args) => { - logInfo(LogModule.LOGGER, "Received request to get log."); + logInfo(LogModule.APP, "Received request to get log."); readLogger(content => { event.reply("Logger.getLog.hook", content); - logInfo(LogModule.LOGGER, "Log data sent to client."); + logInfo(LogModule.APP, "Log data sent to client."); }); }); ipcMain.on("logger.update", (event, args) => { - logInfo(LogModule.LOGGER, "Watching log file for changes."); + logInfo(LogModule.APP, "Watching log file for changes."); fs.watch(logPath, (eventType, filename) => { if (eventType === "change") { - logInfo(LogModule.LOGGER, "Log file changed, reading new content."); + logInfo(LogModule.APP, "Log file changed, reading new content."); readLogger(content => { event.reply("Logger.update.hook", content); - logInfo(LogModule.LOGGER, "Updated log data sent to client."); + logInfo(LogModule.APP, "Updated log data sent to client."); }); } }); }); ipcMain.on("logger.openLog", (event, args) => { - logInfo(LogModule.LOGGER, "Attempting to open log file."); + logInfo(LogModule.APP, "Attempting to open log file."); shell.openPath(logPath).then((errorMessage) => { if (errorMessage) { - logError(LogModule.LOGGER, `Failed to open Logger: ${errorMessage}`); + logError(LogModule.APP, `Failed to open Logger: ${errorMessage}`); event.reply("Logger.openLog.hook", false); } else { - logInfo(LogModule.LOGGER, "Logger opened successfully."); + logInfo(LogModule.APP, "Logger opened successfully."); event.reply("Logger.openLog.hook", true); } }); diff --git a/electron/storage/config.ts b/electron/storage/config.ts index 7c1fbc2..eceba82 100644 --- a/electron/storage/config.ts +++ b/electron/storage/config.ts @@ -2,13 +2,13 @@ import Datastore from "nedb"; import path from "path"; import { app } from "electron"; -const log = require("electron-log"); +import { logInfo, logError, LogModule, logDebug } from "../utils/log"; +import { maskSensitiveData } from "../utils/desensitize"; const configDB = new Datastore({ autoload: true, filename: path.join(app.getPath("userData"), "config.db") }); - /** * 保存 */ @@ -17,8 +17,37 @@ export const saveConfig = ( cb?: (err: Error | null, numberOfUpdated: number, upsert: boolean) => void ) => { document["_id"] = "1"; - log.debug(`保存日志 ${JSON.stringify(document)}`); - configDB.update({ _id: "1" }, document, { upsert: true }, cb); + logDebug( + LogModule.DB, + `Saving configuration to the database. ${JSON.stringify( + maskSensitiveData(document, [ + "serverAddr", + "serverPort", + "authToken", + "user", + "metaToken" + ]) + )}` + ); + configDB.update( + { _id: "1" }, + document, + { upsert: true }, + (err, numberOfUpdated, upsert) => { + if (err) { + logError( + LogModule.DB, + `Error saving configuration: ${err.message}` + ); + } else { + logInfo( + LogModule.DB, + `Configuration saved successfully. Updated: ${numberOfUpdated}, Upsert: ${upsert}` + ); // 添加成功日志 + } + if (cb) cb(err, numberOfUpdated, upsert); + } + ); }; /** @@ -28,9 +57,34 @@ export const saveConfig = ( export const getConfig = ( cb: (err: Error | null, document: FrpConfig) => void ) => { - configDB.findOne({ _id: "1" }, cb); + logInfo(LogModule.DB, "Retrieving configuration from the database."); // 添加信息日志 + configDB.findOne({ _id: "1" }, (err, document) => { + if (err) { + logError( + LogModule.DB, + `Error retrieving configuration: ${err.message}` + ); // 添加错误日志 + } else { + logInfo(LogModule.DB, "Configuration retrieved successfully."); // 添加成功日志 + } + cb(err, document); + }); }; export const clearConfig = (cb?: (err: Error | null, n: number) => void) => { - configDB.remove({}, { multi: true }, cb); -}; \ No newline at end of file + logInfo(LogModule.DB, "Clearing all configurations from the database."); // 添加信息日志 + configDB.remove({}, { multi: true }, (err, n) => { + if (err) { + logError( + LogModule.DB, + `Error clearing configurations: ${err.message}` + ); // 添加错误日志 + } else { + logInfo( + LogModule.DB, + `Successfully cleared configurations. Number of documents removed: ${n}` + ); // 添加成功日志 + } + if (cb) cb(err, n); + }); +}; diff --git a/electron/storage/proxy.ts b/electron/storage/proxy.ts index 7b6b4ca..1dc99c2 100644 --- a/electron/storage/proxy.ts +++ b/electron/storage/proxy.ts @@ -2,90 +2,147 @@ import Datastore from "nedb"; import path from "path"; import { app } from "electron"; -const log = require("electron-log"); +import { logInfo, logError, LogModule, logDebug } from "../utils/log"; const proxyDB = new Datastore({ autoload: true, filename: path.join(app.getPath("userData"), "proxy.db") }); -/** - * 新增代理 - * @param proxy - * @param cb - */ export const insertProxy = ( proxy: Proxy, cb?: (err: Error | null, document: Proxy) => void ) => { - log.debug(`新增代理:${JSON.stringify(proxy)}`); - proxyDB.insert(proxy, cb); + logInfo(LogModule.DB, `Inserting proxy: ${JSON.stringify(proxy)}`); + proxyDB.insert(proxy, (err, document) => { + if (err) { + logError(LogModule.DB, `Error inserting proxy: ${err.message}`); + } else { + logInfo( + LogModule.DB, + `Proxy inserted successfully: ${JSON.stringify(document)}` + ); + } + if (cb) cb(err, document); + }); }; -/** - * 删除代理 - * @param _id - * @param cb - */ export const deleteProxyById = ( _id: string, cb?: (err: Error | null, n: number) => void ) => { - log.debug(`删除代理:${_id}`); - proxyDB.remove({ _id: _id }, cb); + logDebug(`删除代理:${_id}`); + logInfo(LogModule.DB, `Deleting proxy with ID: ${_id}`); + proxyDB.remove({ _id: _id }, (err, n) => { + if (err) { + logError(LogModule.DB, `Error deleting proxy: ${err.message}`); + } else { + logInfo( + LogModule.DB, + `Proxy deleted successfully. Number of documents removed: ${n}` + ); + } + if (cb) cb(err, n); + }); }; -/** - * 修改代理 - */ export const updateProxyById = ( proxy: Proxy, cb?: (err: Error | null, numberOfUpdated: number, upsert: boolean) => void ) => { - log.debug(`修改代理:${proxy}`); - proxyDB.update({ _id: proxy._id }, proxy, {}, cb); + logDebug(`修改代理:${proxy}`); + logInfo(LogModule.DB, `Updating proxy: ${JSON.stringify(proxy)}`); + proxyDB.update( + { _id: proxy._id }, + proxy, + {}, + (err, numberOfUpdated, upsert) => { + if (err) { + logError(LogModule.DB, `Error updating proxy: ${err.message}`); + } else { + logInfo( + LogModule.DB, + `Proxy updated successfully. Updated: ${numberOfUpdated}, Upsert: ${upsert}` + ); + } + if (cb) cb(err, numberOfUpdated, upsert); + } + ); }; -/** - * 查找 - * @param cb - */ export const listProxy = ( callback: (err: Error | null, documents: Proxy[]) => void ) => { - proxyDB.find({}, callback); + logInfo(LogModule.DB, `Listing all proxies`); + proxyDB.find({}, (err, documents) => { + if (err) { + logError(LogModule.DB, `Error listing proxies: ${err.message}`); + } else { + logInfo( + LogModule.DB, + `Proxies listed successfully. Count: ${documents.length}` + ); + } + callback(err, documents); + }); }; -/** - * 根据id查询 - * @param id - * @param callback - */ export const getProxyById = ( id: string, callback: (err: Error | null, document: Proxy) => void ) => { - proxyDB.findOne({ _id: id }, callback); + logInfo(LogModule.DB, `Getting proxy by ID: ${id}`); + proxyDB.findOne({ _id: id }, (err, document) => { + if (err) { + logError(LogModule.DB, `Error getting proxy by ID: ${err.message}`); + } else { + logInfo( + LogModule.DB, + `Proxy retrieved successfully: ${JSON.stringify(document)}` + ); + } + callback(err, document); + }); }; -/** - * 清空代理 - * @param cb - */ export const clearProxy = (cb?: (err: Error | null, n: number) => void) => { - proxyDB.remove({}, { multi: true }, cb); + logInfo(LogModule.DB, `Clearing all proxies`); + proxyDB.remove({}, { multi: true }, (err, n) => { + if (err) { + logError(LogModule.DB, `Error clearing proxies: ${err.message}`); + } else { + logInfo( + LogModule.DB, + `Proxies cleared successfully. Number of documents removed: ${n}` + ); + } + if (cb) cb(err, n); + }); }; -/** - * 更新代理状态 - * @param id id - * @param st 状态 - * @param cb 回调 - */ export const updateProxyStatus = ( id: string, st: boolean, cb?: (err: Error | null, numberOfUpdated: number, upsert: boolean) => void ) => { - proxyDB.update({ _id: id }, { $set: { status: st } }, {}, cb); + logInfo(LogModule.DB, `Updating proxy status for ID: ${id} to ${st}`); + proxyDB.update( + { _id: id }, + { $set: { status: st } }, + {}, + (err, numberOfUpdated, upsert) => { + if (err) { + logError( + LogModule.DB, + `Error updating proxy status: ${err.message}` + ); + } else { + logInfo( + LogModule.DB, + `Proxy status updated successfully. Updated: ${numberOfUpdated}, Upsert: ${upsert}` + ); + } + if (cb) cb(err, numberOfUpdated, upsert); + } + ); }; diff --git a/electron/storage/version.ts b/electron/storage/version.ts index c59413e..10b2c53 100644 --- a/electron/storage/version.ts +++ b/electron/storage/version.ts @@ -2,7 +2,7 @@ import Datastore from "nedb"; import path from "path"; import { app } from "electron"; -const log = require("electron-log"); +import { logInfo, logError, LogModule, logDebug } from "../utils/log"; const versionDB = new Datastore({ autoload: true, @@ -10,7 +10,7 @@ const versionDB = new Datastore({ }); /** - * 新增版本 + * Insert version * @param version * @param cb */ @@ -18,35 +18,73 @@ export const insertVersion = ( version: FrpVersion, cb?: (err: Error | null, document: any) => void ) => { - log.debug(`新增版本:${JSON.stringify(version)}`); - versionDB.insert(version, cb); + logInfo(LogModule.DB, `Inserting version: ${JSON.stringify(version)}`); + versionDB.insert(version, (err, document) => { + if (err) { + logError(LogModule.DB, `Error inserting version: ${err.message}`); + } else { + logInfo(LogModule.DB, `Version inserted successfully: ${JSON.stringify(document)}`); + } + if (cb) cb(err, document); + }); }; /** - * 查找 + * List versions * @param cb */ export const listVersion = ( callback: (err: Error | null, documents: FrpVersion[]) => void ) => { - versionDB.find({}, callback); + logInfo(LogModule.DB, "Listing all versions."); + versionDB.find({}, (err, documents) => { + if (err) { + logError(LogModule.DB, `Error listing versions: ${err.message}`); + } else { + logInfo(LogModule.DB, `Successfully listed versions: ${documents.length} found.`); + } + callback(err, documents); + }); }; export const getVersionById = ( id: number, callback: (err: Error | null, document: FrpVersion) => void ) => { - versionDB.findOne({ id: id }, callback); + logInfo(LogModule.DB, `Retrieving version by ID: ${id}`); + versionDB.findOne({ id: id }, (err, document) => { + if (err) { + logError(LogModule.DB, `Error retrieving version by ID: ${err.message}`); + } else { + logInfo(LogModule.DB, `Version retrieved successfully: ${JSON.stringify(document)}`); + } + callback(err, document); + }); }; export const deleteVersionById = ( id: string, callback: (err: Error | null, document: any) => void ) => { - log.debug(`删除版本:${id}`); - versionDB.remove({ id: id }, callback); + logInfo(LogModule.DB, `Deleting version: ${id}`); + versionDB.remove({ id: id }, (err, document) => { + if (err) { + logError(LogModule.DB, `Error deleting version: ${err.message}`); + } else { + logInfo(LogModule.DB, `Version deleted successfully: ${id}`); + } + callback(err, document); + }); }; export const clearVersion = (cb?: (err: Error | null, n: number) => void) => { - versionDB.remove({}, { multi: true }, cb); + logInfo(LogModule.DB, "Clearing all versions from the database."); + versionDB.remove({}, { multi: true }, (err, n) => { + if (err) { + logError(LogModule.DB, `Error clearing versions: ${err.message}`); + } else { + logInfo(LogModule.DB, `Successfully cleared versions. Number of documents removed: ${n}`); + } + if (cb) cb(err, n); + }); }; diff --git a/electron/utils/log.ts b/electron/utils/log.ts index 7e3730a..9fbd786 100644 --- a/electron/utils/log.ts +++ b/electron/utils/log.ts @@ -3,9 +3,8 @@ import log from "electron-log"; export enum LogModule { APP = "app", FRP_CLIENT = "frpc client", - LOGGER = "logger", GITHUB = "github", - STORAGE = "" + DB = "db" } export const initLog = () => {