feat: 实现 db_enabled/db_path 热重载支持,修复文档格式

- logger-db.ts: 新增 closeDb(),修复 initDb() 支持安全重复调用
- logger.ts: 注册 onConfigReload 回调,db_enabled/db_path 变更后无需重启
- config.yaml.example: 删除「需重启」警告注释,补充热重载说明
- README.md: 修复环境变量表格被 blockquote 截断的格式问题,更新热重载说明
- vue-ui/README.md: 删除「需重启服务」错误说明
- ConfigDrawer.vue: 删除「需重启」提示
This commit is contained in:
huangzhenting
2026-03-23 08:45:21 +08:00
parent 1bc91cac24
commit a84dfd6d03
6 changed files with 39 additions and 11 deletions

View File

@@ -19,7 +19,15 @@ let db: InstanceType<typeof Database> | null = null;
// ==================== 初始化 ====================
export function closeDb(): void {
if (db) {
db.close();
db = null;
}
}
export function initDb(dbPath: string): void {
closeDb(); // 关闭旧连接(幂等,支持热重载重新初始化)
const dir = dirname(dbPath);
if (dir && !existsSync(dir)) {
mkdirSync(dir, { recursive: true });

View File

@@ -16,8 +16,8 @@
import { EventEmitter } from 'events';
import { existsSync, mkdirSync, appendFileSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'fs';
import { join, basename } from 'path';
import { getConfig } from './config.js';
import { initDb, dbInsertRequest, dbGetPayload, dbGetSummaries, dbCountSummaries, dbGetSummaryCount, dbGetStatusCounts, dbGetSummariesSince, dbClear } from './logger-db.js';
import { getConfig, onConfigReload } from './config.js';
import { initDb, closeDb, isDbInitialized, dbInsertRequest, dbGetPayload, dbGetSummaries, dbCountSummaries, dbGetSummaryCount, dbGetStatusCounts, dbGetSummariesSince, dbClear } from './logger-db.js';
// ==================== 类型定义 ====================
@@ -552,6 +552,32 @@ export function loadLogsFromFiles(): void {
}
}
// ==================== SQLite 热重载 ====================
// 注册配置热重载回调,处理 db_enabled / db_path 运行时变更
onConfigReload((newCfg, changes) => {
// 只在 logging 配置变更时处理(避免其他字段变更触发不必要的 DB 重初始化)
if (!changes.some(c => c.startsWith('logging'))) return;
const dbEnabled = newCfg.logging?.db_enabled ?? false;
const dbPath = newCfg.logging?.db_path || './logs/cursor2api.db';
if (dbEnabled) {
// 启用或路径变更重新初始化initDb 内部会先关闭旧连接)
try {
initDb(dbPath);
console.log(`[Logger] SQLite 热重载:已初始化 ${dbPath}`);
} catch (e) {
console.warn('[Logger] SQLite 热重载初始化失败:', e);
}
} else {
// 禁用:关闭连接
if (isDbInitialized()) {
closeDb();
console.log('[Logger] SQLite 热重载:已关闭连接');
}
}
});
/** 清空所有日志(内存 + 文件) */
export function clearAllLogs(): { cleared: number } {
const count = requestSummaries.size;