From 68c8b984adda4ee28429c7a6554cb217810f8e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Sat, 3 Jan 2026 14:51:56 +0800 Subject: [PATCH] Refactor update logging to use logger interface Replaces all console logging in the update process with the ILogWrapper logger interface for consistent logging. Updates applyPendingUpdates to require a logger parameter and propagates this change to all relevant initialization code. Also removes duplicate and unnecessary lines in workflow YAML files. --- .github/workflows/pr-build.yml | 1 - .github/workflows/release.yml | 2 - packages/napcat-framework/napcat.ts | 3 +- packages/napcat-shell/base.ts | 2 +- packages/napcat-webui-backend/index.ts | 2 + .../src/api/UpdateNapCat.ts | 59 ++++++++++--------- 6 files changed, 35 insertions(+), 34 deletions(-) diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index 5ec44812..8b0fd716 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -199,7 +199,6 @@ jobs: status: ${{ steps.build.outcome }} # 构建结果:success/failure error: ${{ steps.build.outputs.error }} # 错误信息(如有) version: ${{ steps.version.outputs.version }} # 构建版本号 - version: ${{ steps.version.outputs.version }} # 构建版本号 steps: # 【安全】先从 base 分支 checkout 构建脚本 - name: Checkout scripts from base diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4f4980b1..1e7a3419 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,8 +6,6 @@ on: tags: - 'v[0-9]*.[0-9]*.[0-9]*' - 'v[0-9]*.[0-9]*.[0-9]*-*' - - 'v[0-9]*.[0-9]*.[0-9]*+*' - - 'v[0-9]*.[0-9]*.[0-9]*-*+*' permissions: write-all diff --git a/packages/napcat-framework/napcat.ts b/packages/napcat-framework/napcat.ts index 75122f6e..23d3648d 100644 --- a/packages/napcat-framework/napcat.ts +++ b/packages/napcat-framework/napcat.ts @@ -34,8 +34,9 @@ export async function NCoreInitFramework ( }); const pathWrapper = new NapCatPathWrapper(); - await applyPendingUpdates(pathWrapper); + const logger = new LogWrapper(pathWrapper.logsPath); + await applyPendingUpdates(pathWrapper, logger); const basicInfoWrapper = new QQBasicInfoWrapper({ logger }); const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVersion()); const nativePacketHandler = new NativePacketHandler({ logger }); // 初始化 NativePacketHandler 用于后续使用 diff --git a/packages/napcat-shell/base.ts b/packages/napcat-shell/base.ts index 75c0b1ad..a8dbac21 100644 --- a/packages/napcat-shell/base.ts +++ b/packages/napcat-shell/base.ts @@ -319,7 +319,7 @@ export async function NCoreInitShell () { const pathWrapper = new NapCatPathWrapper(); const logger = new LogWrapper(pathWrapper.logsPath); handleUncaughtExceptions(logger); - await applyPendingUpdates(pathWrapper); + await applyPendingUpdates(pathWrapper, logger); // 初始化 FFmpeg 服务 await FFmpegService.init(pathWrapper.binaryPath, logger); diff --git a/packages/napcat-webui-backend/index.ts b/packages/napcat-webui-backend/index.ts index f9a238be..4da8e706 100644 --- a/packages/napcat-webui-backend/index.ts +++ b/packages/napcat-webui-backend/index.ts @@ -42,6 +42,7 @@ export let WebUiConfig: WebUiConfigWrapper; export let webUiPathWrapper: NapCatPathWrapper; export let logSubscription: ISubscription; export let statusHelperSubscription: IStatusHelperSubscription; +export let webUiLogger: ILogWrapper | null = null; const MAX_PORT_TRY = 100; export let webUiRuntimePort = 6099; @@ -100,6 +101,7 @@ export async function InitWebUi (logger: ILogWrapper, pathWrapper: NapCatPathWra webUiPathWrapper = pathWrapper; logSubscription = Subscription; statusHelperSubscription = statusSubscription; + webUiLogger = logger; WebUiConfig = new WebUiConfigWrapper(); let config = await WebUiConfig.GetWebUIConfig(); diff --git a/packages/napcat-webui-backend/src/api/UpdateNapCat.ts b/packages/napcat-webui-backend/src/api/UpdateNapCat.ts index 8dc358bd..37a4211a 100644 --- a/packages/napcat-webui-backend/src/api/UpdateNapCat.ts +++ b/packages/napcat-webui-backend/src/api/UpdateNapCat.ts @@ -4,7 +4,7 @@ import * as fs from 'fs'; import * as path from 'path'; import * as https from 'https'; import compressing from 'compressing'; -import { webUiPathWrapper } from '../../index'; +import { webUiPathWrapper, webUiLogger } from '../../index'; import { NapCatPathWrapper } from '@/napcat-common/src/path'; import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data'; import { NapCatCoreWorkingEnv } from '@/napcat-webui-backend/src/types'; @@ -12,6 +12,7 @@ import { getGitHubRelease, findAvailableDownloadUrl } from '@/napcat-common/src/mirror'; +import { ILogWrapper } from '@/napcat-common/src/log-interface'; // 更新请求体接口 interface UpdateRequestBody { @@ -78,18 +79,18 @@ function scanFilesRecursively (dirPath: string, basePath: string = dirPath): Arr * 下载文件(带进度和重试) */ async function downloadFile (url: string, dest: string): Promise { - console.log('Starting download from:', url); + webUiLogger?.log('[NapCat Update] Starting download from:', url); const file = fs.createWriteStream(dest); return new Promise((resolve, reject) => { const request = https.get(url, { headers: { 'User-Agent': 'NapCat-WebUI' } }, (res) => { - console.log('Response status:', res.statusCode); - console.log('Content-Type:', res.headers['content-type']); + webUiLogger?.log('[NapCat Update] Response status:', res.statusCode); + webUiLogger?.log('[NapCat Update] Content-Type:', res.headers['content-type']); if (res.statusCode === 302 || res.statusCode === 301) { - console.log('Following redirect to:', res.headers.location); + webUiLogger?.log('[NapCat Update] Following redirect to:', res.headers.location); file.close(); fs.unlinkSync(dest); downloadFile(res.headers.location!, dest).then(resolve).catch(reject); @@ -106,13 +107,13 @@ async function downloadFile (url: string, dest: string): Promise { res.pipe(file); file.on('finish', () => { file.close(); - console.log('Download completed'); + webUiLogger?.log('[NapCat Update] Download completed'); resolve(); }); }); request.on('error', (err) => { - console.error('Download error:', err); + webUiLogger?.logError('[NapCat Update] Download error:', err); file.close(); fs.unlink(dest, () => { }); reject(err); @@ -131,7 +132,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { // 确定目标版本 tag // 如果指定了版本,使用指定版本;否则使用 'latest' const targetTag = targetVersion || 'latest'; - console.log(`[NapCat Update] Target version: ${targetTag}`); + webUiLogger?.log(`[NapCat Update] Target version: ${targetTag}`); // 使用 mirror 模块获取 release 信息(不依赖 API) // 通过 assetNames 参数直接构建下载 URL,避免调用 GitHub API @@ -147,7 +148,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { // 检查是否需要强制更新(降级警告) const currentVersion = WebUiDataRuntime.GetNapCatVersion(); - console.log(`[NapCat Update] Current version: ${currentVersion}, Target version: ${release.tag_name}`); + webUiLogger?.log(`[NapCat Update] Current version: ${currentVersion}, Target version: ${release.tag_name}`); if (!force && currentVersion) { // 简单的版本比较(可选的降级保护) @@ -165,12 +166,12 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { (targetMajor === currMajor && targetMinor === currMinor && targetPatch < currPatch); if (isDowngrade) { - console.log(`[NapCat Update] Downgrade from ${currentVersion} to ${release.tag_name}, force=${force}`); + webUiLogger?.log(`[NapCat Update] Downgrade from ${currentVersion} to ${release.tag_name}, force=${force}`); // 不阻止降级,只是记录日志 } } - console.log(`[NapCat Update] Updating to version: ${release.tag_name}`); + webUiLogger?.log(`[NapCat Update] Updating to version: ${release.tag_name}`); // 创建临时目录 const tempDir = path.join(webUiPathWrapper.binaryPath, './temp'); @@ -186,20 +187,20 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { timeout: 10000, // 10秒超时 }); - console.log(`[NapCat Update] Using download URL: ${downloadUrl}`); + webUiLogger?.log(`[NapCat Update] Using download URL: ${downloadUrl}`); // 下载zip const zipPath = path.join(tempDir, 'napcat-latest.zip'); - console.log('[NapCat Update] Saving to:', zipPath); + webUiLogger?.log('[NapCat Update] Saving to:', zipPath); await downloadFile(downloadUrl, zipPath); // 检查文件大小 const stats = fs.statSync(zipPath); - console.log('[NapCat Update] Downloaded file size:', stats.size, 'bytes'); + webUiLogger?.log('[NapCat Update] Downloaded file size:', stats.size, 'bytes'); // 解压到临时目录 const extractPath = path.join(tempDir, 'napcat-extract'); - console.log('[NapCat Update] Extracting to:', extractPath); + webUiLogger?.log('[NapCat Update] Extracting to:', extractPath); await compressing.zip.uncompress(zipPath, extractPath); // 获取解压后的实际内容目录(NapCat.Shell.zip直接包含文件,无额外根目录) @@ -220,7 +221,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { // 跳过指定的文件 if (SKIP_UPDATE_FILES.includes(path.basename(fileInfo.relativePath))) { - console.log(`[NapCat Update] Skipping update for ${fileInfo.relativePath}`); + webUiLogger?.log(`[NapCat Update] Skipping update for ${fileInfo.relativePath}`); continue; } @@ -238,7 +239,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { fs.copyFileSync(fileInfo.sourcePath, targetFilePath); } catch (error) { // 如果替换失败,添加到失败列表 - console.log(`[NapCat Update] Failed to update ${targetFilePath}, will retry on next startup:`, error); + webUiLogger?.logError(`[NapCat Update] Failed to update ${targetFilePath}, will retry on next startup:`, error); failedFiles.push({ sourcePath: fileInfo.sourcePath, targetPath: targetFilePath @@ -258,7 +259,7 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { // 保存更新配置文件 const configPath = path.join(webUiPathWrapper.configPath, 'napcat-update.json'); fs.writeFileSync(configPath, JSON.stringify(updateConfig, null, 2)); - console.log(`[NapCat Update] Update config saved for ${failedFiles.length} failed files: ${configPath}`); + webUiLogger?.log(`[NapCat Update] Update config saved for ${failedFiles.length} failed files: ${configPath}`); } // 发送成功响应 @@ -273,12 +274,12 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { }); } catch (error) { - console.error('更新失败:', error); + webUiLogger?.logError('[NapCat Update] 更新失败:', error); sendError(res, '更新失败: ' + (error instanceof Error ? error.message : '未知错误')); } } catch (error: any) { - console.error('更新失败:', error); + webUiLogger?.logError('[NapCat Update] 更新失败:', error); sendError(res, '更新失败: ' + error.message); } }; @@ -288,16 +289,16 @@ export const UpdateNapCatHandler: RequestHandler = async (req, res) => { /** * 应用待处理的更新(在应用启动时调用) */ -export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper): Promise { +export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper, logger: ILogWrapper): Promise { const configPath = path.join(webUiPathWrapper.configPath, 'napcat-update.json'); if (!fs.existsSync(configPath)) { - console.log('No pending updates found'); + logger.log('[NapCat Update] No pending updates found'); return; } try { - console.log('[NapCat Update] Applying pending updates...'); + logger.log('[NapCat Update] Applying pending updates...'); const updateConfig: UpdateConfig = JSON.parse(fs.readFileSync(configPath, 'utf8')); const remainingFiles: Array<{ @@ -309,7 +310,7 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper): try { // 检查源文件是否存在 if (!fs.existsSync(file.sourcePath)) { - console.warn(`[NapCat Update] Source file not found: ${file.sourcePath}`); + logger.logWarn(`[NapCat Update] Source file not found: ${file.sourcePath}`); continue; } @@ -324,10 +325,10 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper): fs.unlinkSync(file.targetPath); // 删除旧文件 } fs.copyFileSync(file.sourcePath, file.targetPath); - console.log(`[NapCat Update] Updated ${path.basename(file.targetPath)} on startup`); + logger.log(`[NapCat Update] Updated ${path.basename(file.targetPath)} on startup`); } catch (error) { - console.error(`[NapCat Update] Failed to update ${file.targetPath} on startup:`, error); + logger.logError(`[NapCat Update] Failed to update ${file.targetPath} on startup:`, error); // 如果仍然失败,保留在列表中 remainingFiles.push(file); } @@ -340,13 +341,13 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper): files: remainingFiles }; fs.writeFileSync(configPath, JSON.stringify(updatedConfig, null, 2)); - console.log(`${remainingFiles.length} files still pending update`); + logger.log(`[NapCat Update] ${remainingFiles.length} files still pending update`); } else { // 所有文件都成功更新,删除配置文件 fs.unlinkSync(configPath); - console.log('[NapCat Update] All pending updates applied successfully'); + logger.log('[NapCat Update] All pending updates applied successfully'); } } catch (error) { - console.error('[NapCat Update] Failed to apply pending updates:', error); + logger.logError('[NapCat Update] Failed to apply pending updates:', error); } }