日志优化
This commit is contained in:
1 parent
fa5bb66d14
commit
aeb403f3c0
21 files changed
+402
-209
No files matched your search
@@ -3,6 +3,8 @@
|
||||
* Executes routine and emergency memory cleanup procedures
|
||||
*/
|
||||
|
||||
const logger = require('../src/utils/logger');
|
||||
|
||||
class CleanupManager {
|
||||
constructor(options = {}) {
|
||||
this.routineInterval = options.routineInterval || 5000; // 5 seconds
|
||||
@@ -21,7 +23,7 @@ class CleanupManager {
|
||||
startRoutineCleanup() {
|
||||
if (this.isRunning) return;
|
||||
|
||||
console.log('🧹 清理管理器已启动');
|
||||
logger.task('清理管理器已启动');
|
||||
this.isRunning = true;
|
||||
|
||||
this.routineIntervalId = setInterval(() => {
|
||||
@@ -35,7 +37,7 @@ class CleanupManager {
|
||||
stopRoutineCleanup() {
|
||||
if (!this.isRunning) return;
|
||||
|
||||
console.log('🧹 清理管理器已停止');
|
||||
logger.task('清理管理器已停止');
|
||||
|
||||
if (this.routineIntervalId) {
|
||||
clearInterval(this.routineIntervalId);
|
||||
@@ -76,7 +78,7 @@ class CleanupManager {
|
||||
|
||||
// 只在内存回收显著时输出日志
|
||||
if (Math.abs(rssReclaimed) > 10) {
|
||||
console.log(`🧹 内存清理: ${rssBefore.toFixed(0)}MB → ${rssAfter.toFixed(0)}MB`);
|
||||
logger.perf(`内存清理: ${rssBefore.toFixed(0)}MB → ${rssAfter.toFixed(0)}MB`);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -87,7 +89,7 @@ class CleanupManager {
|
||||
connectionsCleared: 0
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ 清理失败:', error.message);
|
||||
logger.error('清理失败:', error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -99,7 +101,7 @@ class CleanupManager {
|
||||
* - Force garbage collection multiple times (3+)
|
||||
*/
|
||||
executeEmergencyCleanup() {
|
||||
console.log('🚨 执行紧急内存清理...');
|
||||
logger.task('执行紧急内存清理...');
|
||||
|
||||
const memoryBefore = this.getMemoryStats();
|
||||
|
||||
@@ -110,15 +112,15 @@ class CleanupManager {
|
||||
try {
|
||||
this.dbPool.closeAll();
|
||||
connectionsCleared = 1;
|
||||
console.log(' ✓ 数据库连接已关闭');
|
||||
logger.task('数据库连接已关闭');
|
||||
} catch (error) {
|
||||
console.error(' ✗ 关闭连接失败:', error.message);
|
||||
logger.error('关闭连接失败:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Clear all registered caches
|
||||
const cachesCleared = this.clearAllCaches();
|
||||
console.log(` ✓ 已清理 ${cachesCleared} 个缓存`);
|
||||
logger.task(`已清理 ${cachesCleared} 个缓存`);
|
||||
|
||||
// 3. Force garbage collection multiple times (minimum 3)
|
||||
this.forceGarbageCollection(3);
|
||||
@@ -126,7 +128,7 @@ class CleanupManager {
|
||||
const memoryAfter = this.getMemoryStats();
|
||||
const memoryReclaimed = memoryBefore.heapUsed - memoryAfter.heapUsed;
|
||||
|
||||
console.log(`✅ 紧急清理完成: 回收 ${(memoryReclaimed / 1024 / 1024).toFixed(0)}MB`);
|
||||
logger.task(`紧急清理完成: 回收 ${(memoryReclaimed / 1024 / 1024).toFixed(0)}MB`);
|
||||
|
||||
return {
|
||||
memoryBefore,
|
||||
@@ -136,7 +138,7 @@ class CleanupManager {
|
||||
connectionsCleared
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ 紧急清理失败:', error.message);
|
||||
logger.error('紧急清理失败:', error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -153,7 +155,7 @@ class CleanupManager {
|
||||
try {
|
||||
global.gc();
|
||||
} catch (error) {
|
||||
console.error(` ✗ GC失败 (${i + 1}/${actualIterations}):`, error.message);
|
||||
logger.error(`GC失败 (${i + 1}/${actualIterations}):`, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,7 +174,7 @@ class CleanupManager {
|
||||
cleared++;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ 清理缓存失败 "${name}":`, error.message);
|
||||
logger.error(`清理缓存失败 "${name}":`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +188,7 @@ class CleanupManager {
|
||||
*/
|
||||
registerCache(name, cache) {
|
||||
if (!cache || typeof cache.clear !== 'function') {
|
||||
console.warn(`⚠️ 缓存 "${name}" 无clear()方法`);
|
||||
logger.warn(`缓存 "${name}" 无clear()方法`);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
* Continuously monitors memory usage and triggers cleanup when thresholds are exceeded
|
||||
*/
|
||||
|
||||
const logger = require('../src/utils/logger');
|
||||
|
||||
class MemoryMonitor {
|
||||
constructor(options = {}) {
|
||||
this.warningThreshold = options.warningThreshold || 150 * 1024 * 1024; // 150MB
|
||||
@@ -26,7 +28,7 @@ class MemoryMonitor {
|
||||
start() {
|
||||
if (this.isRunning) return;
|
||||
|
||||
console.log('📊 内存监控已启动');
|
||||
logger.perf('内存监控已启动');
|
||||
|
||||
this.isRunning = true;
|
||||
|
||||
@@ -53,7 +55,7 @@ class MemoryMonitor {
|
||||
stop() {
|
||||
if (!this.isRunning) return;
|
||||
|
||||
console.log('📊 内存监控已停止');
|
||||
logger.perf('内存监控已停止');
|
||||
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
@@ -116,7 +118,6 @@ class MemoryMonitor {
|
||||
|
||||
this.lastWarningTime = now;
|
||||
|
||||
console.warn('⚠️ 内存使用偏高');
|
||||
this.logMemoryStats(stats, 'WARNING');
|
||||
}
|
||||
|
||||
@@ -133,12 +134,11 @@ class MemoryMonitor {
|
||||
|
||||
this.lastDangerTime = now;
|
||||
|
||||
console.error('🚨 内存使用危险!');
|
||||
this.logMemoryStats(stats, 'DANGER');
|
||||
|
||||
// Trigger emergency cleanup if cleanup manager is available
|
||||
if (this.cleanupManager) {
|
||||
console.log('🚨 触发紧急清理...');
|
||||
logger.perf('触发紧急清理...');
|
||||
try {
|
||||
this.cleanupManager.executeEmergencyCleanup();
|
||||
|
||||
@@ -157,7 +157,7 @@ class MemoryMonitor {
|
||||
}
|
||||
}, 1000);
|
||||
} catch (error) {
|
||||
console.error('❌ 紧急清理失败:', error.message);
|
||||
logger.error('紧急清理失败:', error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,10 +172,12 @@ class MemoryMonitor {
|
||||
const externalMB = (stats.external / 1024 / 1024).toFixed(2);
|
||||
const arrayBuffersMB = (stats.arrayBuffers / 1024 / 1024).toFixed(2);
|
||||
|
||||
console.log(`📊 内存状态 [${level}]:`);
|
||||
console.log(` Heap: ${heapUsedMB}/${heapTotalMB} MB`);
|
||||
console.log(` RSS: ${rssMB} MB`);
|
||||
console.log(` External: ${externalMB} MB`);
|
||||
const message = `内存状态 [${level}]: Heap ${heapUsedMB}/${heapTotalMB} MB, RSS ${rssMB} MB`;
|
||||
if (level === 'WARNING' || level === 'DANGER') {
|
||||
logger.warn(message);
|
||||
} else {
|
||||
logger.perf(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+21
-21
@@ -41,7 +41,7 @@ function ensureFolderChain(db, folderPath) {
|
||||
|
||||
// 安全检查:确保 db 对象有 getFolderByPath 方法
|
||||
if (typeof db.getFolderByPath !== 'function') {
|
||||
console.error('❌ db.getFolderByPath 不是函数');
|
||||
logger.error('db.getFolderByPath 不是函数');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(full)) {
|
||||
console.warn(`File not found, skipping: ${full}`);
|
||||
logger.warn(`File not found, skipping: ${full}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
}
|
||||
results.added++;
|
||||
} catch (error) {
|
||||
console.error(`❌ 处理新增文件失败 ${file}:`, error.message);
|
||||
logger.error(`处理新增文件失败 ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(full)) {
|
||||
console.warn(`File not found, skipping: ${full}`);
|
||||
logger.warn(`File not found, skipping: ${full}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
affectedFolders.add(folder);
|
||||
results.modified++;
|
||||
} catch (error) {
|
||||
console.error(`❌ 处理修改文件失败 ${file}:`, error.message);
|
||||
logger.error(`处理修改文件失败 ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +160,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
}
|
||||
results.deleted++;
|
||||
} catch (error) {
|
||||
console.error(`❌ 删除文件失败 ${file}:`, error.message);
|
||||
logger.error(`删除文件失败 ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
if (parent && parent !== '.') affectedFolders.add(parent);
|
||||
results.foldersRemoved++;
|
||||
} catch (error) {
|
||||
console.error(`❌ 删除目录失败 ${dir}:`, error.message);
|
||||
logger.error(`删除目录失败 ${dir}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,14 +185,14 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
try {
|
||||
db.updateFolderImageCount(folderPath);
|
||||
} catch (error) {
|
||||
console.error(`❌ 更新文件夹计数失败 ${folderPath}:`, error.message);
|
||||
logger.error(`更新文件夹计数失败 ${folderPath}:`, error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('❌ 应用变化失败:', error.message);
|
||||
logger.error('应用变化失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -312,7 +312,7 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) {
|
||||
|
||||
return { status: 'processed', path: relativePath };
|
||||
} catch (error) {
|
||||
console.error('❌ 处理图片失败:', path.basename(imagePath), error.message);
|
||||
logger.error('处理图片失败:', path.basename(imagePath), error.message);
|
||||
return { status: 'error', path: imagePath, error: error.message };
|
||||
}
|
||||
}
|
||||
@@ -501,7 +501,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
|
||||
// 强制 GC(如果可用)
|
||||
if (global.gc) {
|
||||
global.gc();
|
||||
logger.debug('内存已清理');
|
||||
logger.perf('内存已清理');
|
||||
}
|
||||
|
||||
// 标记扫描完成
|
||||
@@ -543,14 +543,14 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
const toCheck = [...currentPaths].filter(p => dbPaths.has(p));
|
||||
let toDelete = [...dbPaths].filter(p => !currentPaths.has(p));
|
||||
|
||||
console.log(`🔄 同步: +${toAdd.length} 检查${toCheck.length} -${toDelete.length}`);
|
||||
logger.perf(`同步: +${toAdd.length} 检查${toCheck.length} -${toDelete.length}`);
|
||||
|
||||
// 安全检查:如果要删除的文件数量超过数据库中文件的50%,可能是路径匹配问题
|
||||
const dbImageCount = dbPaths.size;
|
||||
if (toDelete.length > 0 && dbImageCount > 0) {
|
||||
const deleteRatio = toDelete.length / dbImageCount;
|
||||
if (deleteRatio > 0.5 && toDelete.length > 10) {
|
||||
console.warn(`⚠️ 安全检查: 跳过删除 ${toDelete.length}/${dbImageCount} 个文件 (${(deleteRatio * 100).toFixed(1)}%)`);
|
||||
logger.warn(`安全检查: 跳过删除 ${toDelete.length}/${dbImageCount} 个文件 (${(deleteRatio * 100).toFixed(1)}%)`);
|
||||
toDelete = [];
|
||||
}
|
||||
}
|
||||
@@ -591,7 +591,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
}).length;
|
||||
|
||||
if (modifiedCount > 0) {
|
||||
console.log(`📝 发现 ${modifiedCount} 个修改文件`);
|
||||
logger.perf(`发现 ${modifiedCount} 个修改文件`);
|
||||
}
|
||||
|
||||
// Delete removed files
|
||||
@@ -602,7 +602,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
|
||||
// Rebuild folder structure if there are changes or forced
|
||||
if (toAdd.length > 0 || toDelete.length > 0 || forceRebuildFolders) {
|
||||
console.log('📂 重建文件夹结构...');
|
||||
logger.perf('重建文件夹结构...');
|
||||
|
||||
// Get current folder structure from file system
|
||||
const currentFolders = await getFolderStructure(libraryPath);
|
||||
@@ -627,7 +627,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
});
|
||||
|
||||
if (foldersToAdd.length > 0 || foldersToDelete.length > 0) {
|
||||
console.log(`📂 文件夹变化: +${foldersToAdd.length} -${foldersToDelete.length}`);
|
||||
logger.perf(`文件夹变化: +${foldersToAdd.length} -${foldersToDelete.length}`);
|
||||
}
|
||||
|
||||
// Update folder image counts
|
||||
@@ -653,7 +653,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
}
|
||||
|
||||
const totalTime = (Date.now() - startTime) / 1000;
|
||||
console.log(`✅ 同步完成 (${totalTime.toFixed(1)}秒)`);
|
||||
logger.perf(`同步完成 (${totalTime.toFixed(1)}秒)`);
|
||||
|
||||
// 清理 Sharp 缓存
|
||||
clearSharpCache();
|
||||
@@ -664,7 +664,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
deleted: toDelete.length
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ 同步失败:', error.message);
|
||||
logger.error('同步失败:', error.message);
|
||||
clearSharpCache();
|
||||
throw error;
|
||||
}
|
||||
@@ -698,7 +698,7 @@ async function quickSync(libraryPath, db) {
|
||||
if (toDelete.length > 0 && dbImageCount > 0) {
|
||||
const deleteRatio = toDelete.length / dbImageCount;
|
||||
if (deleteRatio > 0.5 && toDelete.length > 10) {
|
||||
console.warn(`⚠️ 跳过删除 ${toDelete.length} 个文件`);
|
||||
logger.warn(`跳过删除 ${toDelete.length} 个文件`);
|
||||
toDelete = [];
|
||||
}
|
||||
}
|
||||
@@ -714,7 +714,7 @@ async function quickSync(libraryPath, db) {
|
||||
}
|
||||
await processImage(fullPath, libraryPath, db);
|
||||
} catch (err) {
|
||||
console.error(`❌ 添加失败 ${relativePath}:`, err.message);
|
||||
logger.error(`添加失败 ${relativePath}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -730,7 +730,7 @@ async function quickSync(libraryPath, db) {
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
if (toAdd.length > 0 || toDelete.length > 0) {
|
||||
console.log(`⚡ 快速同步: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`);
|
||||
logger.perf(`快速同步: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`);
|
||||
// 有变化时清理 Sharp 缓存
|
||||
clearSharpCache();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user