日志优化
This commit is contained in:
1 parent
fa5bb66d14
commit
aeb403f3c0
21 files changed
+402
-209
No files matched your search
@@ -10,6 +10,7 @@ const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { asyncHandler } = require('../middleware/errorHandler');
|
||||
const { processImage } = require('../../utils/scanner');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
// 配置 multer 使用内存存储
|
||||
const storage = multer.memoryStorage();
|
||||
|
||||
@@ -39,7 +39,7 @@ class FileService {
|
||||
const originalPath = path.join(libraryPath, item.path);
|
||||
const metaPath = backupPath + '.meta.json';
|
||||
|
||||
console.log(`🔄 开始恢复: ${item.path} (${item.type})`);
|
||||
logger.fileOp(`开始恢复: ${item.path} (${item.type})`);
|
||||
|
||||
// 检查备份是否存在
|
||||
if (!fs.existsSync(backupPath)) {
|
||||
@@ -61,10 +61,9 @@ class FileService {
|
||||
const metaContent = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
|
||||
imageRecords = metaContent.imageRecords;
|
||||
folderRecords = metaContent.folderRecords;
|
||||
console.log(` 读取到 ${Array.isArray(imageRecords) ? imageRecords.length : (imageRecords ? 1 : 0)} 条图片记录`);
|
||||
console.log(` 读取到 ${folderRecords ? folderRecords.length : 0} 条文件夹记录`);
|
||||
logger.fileOp(`读取meta: 图片${Array.isArray(imageRecords) ? imageRecords.length : (imageRecords ? 1 : 0)}条, 文件夹${folderRecords ? folderRecords.length : 0}条`);
|
||||
} catch (error) {
|
||||
console.warn(`读取meta失败 ${metaPath}:`, error);
|
||||
logger.warn(`读取meta失败 ${metaPath}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +71,7 @@ class FileService {
|
||||
try {
|
||||
fs.renameSync(backupPath, originalPath);
|
||||
} catch (renameError) {
|
||||
console.log(` ⚠️ rename失败,使用复制方式`);
|
||||
logger.fileOp('rename失败,使用复制方式');
|
||||
// rename 失败时使用复制+删除
|
||||
if (item.type === 'folder') {
|
||||
this._copyDirSync(backupPath, originalPath);
|
||||
@@ -98,7 +97,7 @@ class FileService {
|
||||
folderRecord.last_scan || Date.now()
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn(`恢复文件夹记录失败: ${folderRecord.path}`, error);
|
||||
logger.warn(`恢复文件夹记录失败: ${folderRecord.path}`, error.message);
|
||||
}
|
||||
}
|
||||
} else if (item.type === 'folder') {
|
||||
@@ -116,9 +115,9 @@ class FileService {
|
||||
0,
|
||||
Date.now()
|
||||
);
|
||||
console.log(` 创建空文件夹记录: ${item.path}`);
|
||||
logger.fileOp(`创建空文件夹记录: ${item.path}`);
|
||||
} catch (error) {
|
||||
console.warn(`创建文件夹记录失败: ${item.path}`, error);
|
||||
logger.warn(`创建文件夹记录失败: ${item.path}`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,7 +127,7 @@ class FileService {
|
||||
try {
|
||||
db.insertImage(record);
|
||||
} catch (error) {
|
||||
console.warn(`恢复图片记录失败: ${record.path}`, error);
|
||||
logger.warn(`恢复图片记录失败: ${record.path}`, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,9 +138,9 @@ class FileService {
|
||||
}
|
||||
|
||||
results.success.push(item.path);
|
||||
console.log(`✅ 恢复成功: ${item.path}`);
|
||||
logger.fileOp(`恢复成功: ${item.path}`);
|
||||
} catch (error) {
|
||||
console.error(`恢复失败 ${item.path}:`, error);
|
||||
logger.error(`恢复失败 ${item.path}:`, error.message);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
}
|
||||
}
|
||||
@@ -214,7 +213,7 @@ class FileService {
|
||||
if (fs.existsSync(thumbnailFullPath)) {
|
||||
fs.unlinkSync(thumbnailFullPath);
|
||||
thumbnailsCleaned++;
|
||||
logger.debug(`已清理缩略图: ${record.thumbnail_path}`);
|
||||
logger.fileOp(`清理缩略图: ${record.thumbnail_path}`);
|
||||
}
|
||||
} catch (thumbError) {
|
||||
logger.warn(`清理缩略图失败 ${record.thumbnail_path}:`, thumbError.message);
|
||||
@@ -293,7 +292,7 @@ class FileService {
|
||||
// 根目录也删除(如果完全为空)
|
||||
try {
|
||||
fs.rmdirSync(dir);
|
||||
logger.debug(`已删除空的备份目录: ${TEMP_BACKUP_DIR}`);
|
||||
logger.fileOp(`删除空的备份目录: ${TEMP_BACKUP_DIR}`);
|
||||
} catch (error) {
|
||||
// 忽略根目录删除失败
|
||||
}
|
||||
@@ -302,7 +301,7 @@ class FileService {
|
||||
try {
|
||||
fs.rmdirSync(dir);
|
||||
const relativePath = path.relative(backupDir, dir);
|
||||
logger.debug(`已删除空文件夹: ${relativePath}`);
|
||||
logger.fileOp(`删除空文件夹: ${relativePath}`);
|
||||
} catch (error) {
|
||||
// 忽略删除失败(可能权限问题)
|
||||
}
|
||||
@@ -353,13 +352,13 @@ class FileService {
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
if (item.type === 'folder') {
|
||||
// 物理文件夹已不存在:视为只需要清理数据库中的“空壳”记录
|
||||
console.warn(`目标文件夹不存在,仅清理数据库记录: ${item.path}`);
|
||||
logger.fileOp(`目标文件夹不存在,仅清理数据库记录: ${item.path}`);
|
||||
try {
|
||||
db.deleteImagesByFolderPrefix(item.path);
|
||||
db.deleteFoldersByPrefix(item.path);
|
||||
results.success.push(item.path);
|
||||
} catch (e) {
|
||||
console.error(`清理不存在文件夹的数据库记录失败 ${item.path}:`, e.message);
|
||||
logger.error(`清理不存在文件夹的数据库记录失败 ${item.path}:`, e.message);
|
||||
results.failed.push({ path: item.path, error: e.message });
|
||||
}
|
||||
} else {
|
||||
@@ -389,7 +388,7 @@ class FileService {
|
||||
fs.renameSync(fullPath, backupPath);
|
||||
} catch (renameError) {
|
||||
// rename 失败(可能是权限问题或跨磁盘),使用复制+删除
|
||||
console.log(`⚠️ rename失败,使用复制方式: ${item.path}`);
|
||||
logger.fileOp(`rename失败,使用复制方式: ${item.path}`);
|
||||
if (item.type === 'folder') {
|
||||
// 文件夹:递归复制
|
||||
this._copyDirSync(fullPath, backupPath);
|
||||
@@ -410,7 +409,7 @@ class FileService {
|
||||
type: item.type
|
||||
}));
|
||||
|
||||
console.log(`📦 已移入临时文件夹: ${item.path}`);
|
||||
logger.fileOp(`已移入临时文件夹: ${item.path}`);
|
||||
|
||||
// 删除数据库记录前,先保存到meta(恢复时需要)
|
||||
let imageRecords = null;
|
||||
@@ -422,7 +421,7 @@ class FileService {
|
||||
const stmt = db.db.prepare('SELECT * FROM folders WHERE path = ? OR path LIKE ?');
|
||||
folderRecords = stmt.all(item.path, `${item.path}/%`);
|
||||
|
||||
console.log(`🔍 删除文件夹: ${item.path} (图片:${imageRecords?.length || 0}, 子文件夹:${folderRecords?.length || 0})`);
|
||||
logger.fileOp(`删除文件夹: ${item.path} (图片:${imageRecords?.length || 0}, 子文件夹:${folderRecords?.length || 0})`);
|
||||
|
||||
// 删除数据库记录
|
||||
db.deleteImagesByFolderPrefix(item.path);
|
||||
@@ -448,7 +447,7 @@ class FileService {
|
||||
|
||||
results.success.push(item.path);
|
||||
} catch (error) {
|
||||
console.error(`删除失败 ${item.path}:`, error.message);
|
||||
logger.error(`删除失败 ${item.path}:`, error.message);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
}
|
||||
}
|
||||
@@ -601,11 +600,11 @@ class FileService {
|
||||
|
||||
if (conflictAction === 'skip') {
|
||||
// 跳过冲突文件
|
||||
console.log(`⏭️ 跳过冲突: ${fileName}`);
|
||||
logger.fileOp(`跳过冲突: ${fileName}`);
|
||||
continue;
|
||||
} else if (conflictAction === 'replace') {
|
||||
// 覆盖:先删除目标文件/文件夹
|
||||
console.log(`🔄 覆盖: ${fileName}`);
|
||||
logger.fileOp(`覆盖: ${fileName}`);
|
||||
if (fs.statSync(newFullPath).isDirectory()) {
|
||||
// 删除目标物理目录
|
||||
fs.rmSync(newFullPath, { recursive: true, force: true });
|
||||
@@ -637,7 +636,7 @@ class FileService {
|
||||
newFullPath = path.join(libraryPath, newRelativeFolder);
|
||||
counter++;
|
||||
}
|
||||
console.log(`✏️ 重命名为: ${path.basename(newFullPath)}`);
|
||||
logger.fileOp(`重命名为: ${path.basename(newFullPath)}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -709,7 +708,7 @@ class FileService {
|
||||
results.success.push({ oldPath, newPath: newRelativePath });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`移动失败 ${item.path}:`, error.message);
|
||||
logger.error(`移动失败 ${item.path}:`, error.message);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
}
|
||||
}
|
||||
@@ -763,11 +762,11 @@ class FileService {
|
||||
|
||||
if (conflictAction === 'skip') {
|
||||
// 跳过:源和目标相同,直接跳过
|
||||
console.log(`⏭️ 跳过(源和目标相同): ${fileName}`);
|
||||
logger.fileOp(`跳过(源和目标相同): ${fileName}`);
|
||||
continue;
|
||||
} else if (conflictAction === 'replace') {
|
||||
// 覆盖:源和目标相同,无法覆盖自己,跳过
|
||||
console.log(`⏭️ 跳过(无法覆盖自己): ${fileName}`);
|
||||
logger.fileOp(`跳过(无法覆盖自己): ${fileName}`);
|
||||
continue;
|
||||
} else if (conflictAction === 'rename') {
|
||||
// 重命名:自动编号创建副本
|
||||
@@ -782,7 +781,7 @@ class FileService {
|
||||
finalDstPath = path.join(targetFullPath, numberedName);
|
||||
counter++;
|
||||
}
|
||||
console.log(`✏️ 创建副本: ${path.basename(finalDstPath)}`);
|
||||
logger.fileOp(`创建副本: ${path.basename(finalDstPath)}`);
|
||||
}
|
||||
} else if (fs.existsSync(dstFullPath)) {
|
||||
// 目标文件存在但与源不同
|
||||
@@ -790,11 +789,11 @@ class FileService {
|
||||
|
||||
if (conflictAction === 'skip') {
|
||||
// 跳过冲突文件
|
||||
console.log(`⏭️ 跳过冲突文件: ${fileName}`);
|
||||
logger.fileOp(`跳过冲突文件: ${fileName}`);
|
||||
continue;
|
||||
} else if (conflictAction === 'replace') {
|
||||
// 覆盖:先删除目标文件/文件夹
|
||||
console.log(`🔄 覆盖文件: ${fileName}`);
|
||||
logger.fileOp(`覆盖文件: ${fileName}`);
|
||||
if (fs.statSync(dstFullPath).isDirectory()) {
|
||||
fs.rmSync(dstFullPath, { recursive: true, force: true });
|
||||
} else {
|
||||
@@ -813,7 +812,7 @@ class FileService {
|
||||
finalDstPath = path.join(targetFullPath, numberedName);
|
||||
counter++;
|
||||
}
|
||||
console.log(`✏️ 重命名为: ${path.basename(finalDstPath)}`);
|
||||
logger.fileOp(`重命名为: ${path.basename(finalDstPath)}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -834,9 +833,9 @@ class FileService {
|
||||
|
||||
const newRelativePath = path.relative(libraryPath, finalDstPath).replace(/\\/g, '/');
|
||||
results.success.push({ oldPath: item.path, newPath: newRelativePath });
|
||||
console.log(`✅ 复制成功: ${item.path} → ${newRelativePath}`);
|
||||
logger.fileOp(`复制成功: ${item.path} → ${newRelativePath}`);
|
||||
} catch (error) {
|
||||
console.error(`复制失败 ${item.path}:`, error.message);
|
||||
logger.error(`复制失败 ${item.path}:`, error.message);
|
||||
results.failed.push({ path: item.path, error: error.message });
|
||||
}
|
||||
}
|
||||
@@ -874,7 +873,7 @@ class FileService {
|
||||
try {
|
||||
await processImage(fullPath, libraryPath, db);
|
||||
} catch (error) {
|
||||
console.warn(`处理图片失败 ${entry.name}:`, error.message);
|
||||
logger.warn(`处理图片失败 ${entry.name}:`, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1028,7 +1027,7 @@ class FileService {
|
||||
|
||||
// 创建文件夹
|
||||
fs.mkdirSync(fullPath, { recursive: true });
|
||||
console.log(`📁 创建文件夹: ${folderPath}`);
|
||||
logger.fileOp(`创建文件夹: ${folderPath}`);
|
||||
|
||||
// 添加到数据库
|
||||
const normalizedPath = folderPath.replace(/\\/g, '/');
|
||||
@@ -1082,7 +1081,7 @@ class FileService {
|
||||
fs.unlinkSync(thumbnailFullPath);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`删除缩略图失败: ${error.message}`);
|
||||
logger.warn(`删除缩略图失败: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,10 +41,10 @@ class LibraryService {
|
||||
|
||||
// 规范化路径
|
||||
const normalizedPath = path.normalize(libraryPath);
|
||||
console.log(`[LibraryService] Creating library: name=${name}, path=${normalizedPath}`);
|
||||
logger.system(`创建素材库: name=${name}, path=${normalizedPath}`);
|
||||
|
||||
if (!fs.existsSync(normalizedPath)) {
|
||||
console.log(`[LibraryService] Path does not exist: ${normalizedPath}`);
|
||||
logger.warn(`路径不存在: ${normalizedPath}`);
|
||||
throw new ValidationError('Path does not exist', 'path');
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ class LibraryService {
|
||||
fs.writeFileSync(testFile, 'test');
|
||||
fs.unlinkSync(testFile);
|
||||
} catch (writeError) {
|
||||
console.log(`[LibraryService] No write permission: ${normalizedPath}`);
|
||||
logger.warn(`无写入权限: ${normalizedPath}`);
|
||||
throw new ValidationError(
|
||||
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
|
||||
'permission'
|
||||
@@ -67,7 +67,7 @@ class LibraryService {
|
||||
}
|
||||
} catch (readError) {
|
||||
if (readError.code === 'EACCES' || readError.code === 'EPERM') {
|
||||
console.log(`[LibraryService] No access permission: ${normalizedPath}`);
|
||||
logger.warn(`无访问权限: ${normalizedPath}`);
|
||||
throw new ValidationError(
|
||||
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
|
||||
'permission'
|
||||
@@ -186,7 +186,7 @@ class LibraryService {
|
||||
try {
|
||||
this.lightweightWatcher.watch(id, library.path, library.name, this.io);
|
||||
} catch (e) {
|
||||
console.warn('Failed to start file watcher:', e.message);
|
||||
logger.warn('启动文件监控失败:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+135
-11
@@ -1,5 +1,14 @@
|
||||
/**
|
||||
* 简单的日志工具
|
||||
* FlyPic 后端日志系统
|
||||
* 专注于系统级和性能监控日志
|
||||
*
|
||||
* 日志分类:
|
||||
* - SYSTEM: 系统事件(启动、关闭、配置)
|
||||
* - PERF: 性能监控(扫描速度、内存使用)
|
||||
* - DB: 数据库操作(重要查询、批量操作)
|
||||
* - TASK: 定时任务(清理任务、同步任务)
|
||||
* - API: API请求(仅记录关键操作和错误)
|
||||
* - ERROR: 错误(系统异常、崩溃)
|
||||
*/
|
||||
|
||||
const LOG_LEVELS = {
|
||||
@@ -9,23 +18,138 @@ const LOG_LEVELS = {
|
||||
ERROR: 3
|
||||
};
|
||||
|
||||
// 日志类别配置(带emoji)
|
||||
const LOG_CATEGORIES = {
|
||||
SYSTEM: '🚀',
|
||||
PERF: '⚡',
|
||||
DB: '💾',
|
||||
TASK: '🔄',
|
||||
API: '🌐',
|
||||
FILE: '📁',
|
||||
ERROR: '❌'
|
||||
};
|
||||
|
||||
const currentLevel = process.env.LOG_LEVEL
|
||||
? LOG_LEVELS[process.env.LOG_LEVEL.toUpperCase()]
|
||||
: LOG_LEVELS.INFO;
|
||||
|
||||
function log(level, message, ...args) {
|
||||
/**
|
||||
* 格式化时间戳
|
||||
*/
|
||||
function getTimestamp() {
|
||||
const now = new Date();
|
||||
return now.toISOString().replace('T', ' ').slice(0, 19);
|
||||
}
|
||||
|
||||
/**
|
||||
* 基础日志输出
|
||||
*/
|
||||
function log(level, category, message, ...args) {
|
||||
if (LOG_LEVELS[level] >= currentLevel) {
|
||||
const timestamp = new Date().toISOString();
|
||||
const prefix = `[${timestamp}] [${level}]`;
|
||||
console.log(prefix, message, ...args);
|
||||
const emoji = LOG_CATEGORIES[category] || '📝';
|
||||
const timestamp = getTimestamp();
|
||||
const prefix = `[${timestamp}] ${emoji} [${level}]`;
|
||||
|
||||
const method = level === 'ERROR' ? 'error' : level === 'WARN' ? 'warn' : 'log';
|
||||
console[method](prefix, message, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
const logger = {
|
||||
debug: (message, ...args) => log('DEBUG', message, ...args),
|
||||
info: (message, ...args) => log('INFO', message, ...args),
|
||||
warn: (message, ...args) => log('WARN', message, ...args),
|
||||
error: (message, ...args) => log('ERROR', message, ...args)
|
||||
};
|
||||
/**
|
||||
* 日志器类
|
||||
*/
|
||||
class Logger {
|
||||
// ==================== 系统日志 ====================
|
||||
|
||||
/**
|
||||
* 系统级日志(启动、关闭、配置)
|
||||
* @example logger.system('服务启动', { port: 5002 })
|
||||
*/
|
||||
system(message, ...args) {
|
||||
log('INFO', 'SYSTEM', message, ...args);
|
||||
}
|
||||
|
||||
// ==================== 性能日志 ====================
|
||||
|
||||
/**
|
||||
* 性能监控日志(扫描速度、内存使用)
|
||||
* @example logger.perf('扫描完成', { count: 1000, time: 5.2 })
|
||||
*/
|
||||
perf(message, ...args) {
|
||||
log('INFO', 'PERF', message, ...args);
|
||||
}
|
||||
|
||||
// ==================== 数据库日志 ====================
|
||||
|
||||
/**
|
||||
* 数据库操作日志(重要查询、批量操作)
|
||||
* @example logger.db('批量插入图片', { count: 50 })
|
||||
*/
|
||||
db(message, ...args) {
|
||||
log('DEBUG', 'DB', message, ...args);
|
||||
}
|
||||
|
||||
// ==================== 任务日志 ====================
|
||||
|
||||
/**
|
||||
* 定时任务日志(清理任务、同步任务)
|
||||
* @example logger.task('开始清理过期文件', { count: 10 })
|
||||
*/
|
||||
task(message, ...args) {
|
||||
log('INFO', 'TASK', message, ...args);
|
||||
}
|
||||
|
||||
// ==================== API日志 ====================
|
||||
|
||||
/**
|
||||
* API请求日志(仅记录关键操作)
|
||||
* @example logger.api('删除文件', { count: 3, user: 'admin' })
|
||||
*/
|
||||
api(message, ...args) {
|
||||
log('INFO', 'API', message, ...args);
|
||||
}
|
||||
|
||||
// ==================== 文件操作日志 ====================
|
||||
|
||||
/**
|
||||
* 文件操作日志
|
||||
* @example logger.fileOp('移动文件', { from: '/a', to: '/b' })
|
||||
*/
|
||||
fileOp(message, ...args) {
|
||||
log('DEBUG', 'FILE', message, ...args);
|
||||
}
|
||||
|
||||
// ==================== 通用日志 ====================
|
||||
|
||||
/**
|
||||
* 调试日志(仅DEBUG级别)
|
||||
*/
|
||||
debug(message, ...args) {
|
||||
log('DEBUG', 'SYSTEM', message, ...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 信息日志
|
||||
*/
|
||||
info(message, ...args) {
|
||||
log('INFO', 'SYSTEM', message, ...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 警告日志
|
||||
*/
|
||||
warn(message, ...args) {
|
||||
log('WARN', 'ERROR', message, ...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误日志
|
||||
*/
|
||||
error(message, ...args) {
|
||||
log('ERROR', 'ERROR', message, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
const logger = new Logger();
|
||||
|
||||
module.exports = logger;
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
+14
-11
@@ -12,6 +12,9 @@ import MainContent from './components/MainContent';
|
||||
import RightPanel from './components/RightPanel';
|
||||
import Header from './components/Header';
|
||||
import LibraryMissingModal from './components/LibraryMissingModal';
|
||||
import { createLogger } from './utils/logger';
|
||||
|
||||
const logger = createLogger('App');
|
||||
|
||||
function App() {
|
||||
// 使用统一的主题管理 Hook
|
||||
@@ -94,7 +97,7 @@ function App() {
|
||||
});
|
||||
|
||||
socket.on('connect_error', (error) => {
|
||||
console.error('❌ 连接错误:', error.message);
|
||||
logger.error('Socket连接错误:', error.message);
|
||||
});
|
||||
|
||||
socket.on('scanProgress', (progress) => {
|
||||
@@ -136,7 +139,7 @@ function App() {
|
||||
useImageStore.getState().setTotalImageCount(statsRes.total || 0);
|
||||
useImageStore.getState().setTotalSize(statsRes.totalSize || 0);
|
||||
}).catch(err => {
|
||||
console.error('❌ 加载数据失败:', err.message);
|
||||
logger.error('扫描完成后加载数据失败:', err.message);
|
||||
}).finally(() => {
|
||||
setScanProgress(null);
|
||||
});
|
||||
@@ -147,7 +150,7 @@ function App() {
|
||||
|
||||
socket.on('scanError', ({ libraryId, error }) => {
|
||||
setScanProgress(null);
|
||||
console.error('❌ 扫描错误:', error);
|
||||
logger.error('扫描错误:', error);
|
||||
});
|
||||
|
||||
|
||||
@@ -175,7 +178,7 @@ function App() {
|
||||
useImageStore.getState().setTotalImageCount(statsResponse.total || 0);
|
||||
useImageStore.getState().setTotalSize(statsResponse.totalSize || 0);
|
||||
} catch (error) {
|
||||
console.error('❌ 加载文件夹失败:', error.message);
|
||||
logger.error('加载文件夹失败:', error.message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -223,7 +226,7 @@ function App() {
|
||||
return; // 不继续加载
|
||||
}
|
||||
} catch (validateError) {
|
||||
console.warn('验证素材库路径失败:', validateError.message);
|
||||
logger.warn('验证素材库路径失败:', validateError.message);
|
||||
// 验证失败时继续正常加载
|
||||
}
|
||||
|
||||
@@ -243,7 +246,7 @@ function App() {
|
||||
setIsConnecting(false);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ 加载素材库失败 (${retryCount + 1}/${maxRetries}):`, error.message);
|
||||
logger.error(`加载素材库失败 (${retryCount + 1}/${maxRetries}):`, error.message);
|
||||
|
||||
if (retryCount < maxRetries - 1) {
|
||||
// 重试
|
||||
@@ -270,7 +273,7 @@ function App() {
|
||||
const response = await imageAPI.search(libraryId, params);
|
||||
useImageStore.getState().setImages(response.images);
|
||||
} catch (error) {
|
||||
console.error('❌ 加载图片失败:', error.message);
|
||||
logger.error('加载图片失败:', error.message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -282,7 +285,7 @@ function App() {
|
||||
rightPanelWidth: right
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('❌ 保存面板宽度失败:', error.message);
|
||||
logger.error('保存面板宽度失败:', error.message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -434,7 +437,7 @@ function App() {
|
||||
await scanAPI.fullScan(missingLibrary.id);
|
||||
// 扫描会通过 Socket.IO 推送进度
|
||||
} catch (error) {
|
||||
console.error('启动扫描失败:', error.message);
|
||||
logger.error('启动扫描失败:', error.message);
|
||||
alert('启动扫描失败: ' + error.message);
|
||||
}
|
||||
};
|
||||
@@ -454,7 +457,7 @@ function App() {
|
||||
useImageStore.getState().setTotalImageCount(0);
|
||||
useImageStore.getState().setSelectedFolder(null);
|
||||
} catch (error) {
|
||||
console.error('移除素材库失败:', error.message);
|
||||
logger.error('移除素材库失败:', error.message);
|
||||
}
|
||||
|
||||
// 关闭弹窗
|
||||
@@ -474,7 +477,7 @@ function App() {
|
||||
await libraryAPI.remove(missingLibrary.id);
|
||||
removeLibrary(missingLibrary.id);
|
||||
} catch (error) {
|
||||
console.error('移除素材库失败:', error.message);
|
||||
logger.error('移除素材库失败:', error.message);
|
||||
}
|
||||
|
||||
// 关闭弹窗
|
||||
|
||||
@@ -6,6 +6,9 @@ import { useUIStore } from '../stores/useUIStore';
|
||||
import { useScanStore } from '../stores/useScanStore';
|
||||
import { useTheme } from '../hooks/useTheme';
|
||||
import { libraryAPI, scanAPI, watchAPI } from '../api';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const logger = createLogger('Header');
|
||||
|
||||
function Header() {
|
||||
const { currentLibraryId } = useLibraryStore();
|
||||
|
||||
@@ -137,27 +137,23 @@ function ImageWaterfall() {
|
||||
useImageKeyboard({
|
||||
onDelete: handleQuickDeleteWithUndoStack,
|
||||
onUndo: async () => {
|
||||
console.log('🔍 撤销前状态:', {
|
||||
undoStack: [...undoStack],
|
||||
moveUndoHistory: moveUndoHistory.length,
|
||||
deleteUndoHistory: undoHistory.length
|
||||
});
|
||||
// 检查撤销栏状态
|
||||
|
||||
if (undoStack.length === 0) return;
|
||||
const last = undoStack[undoStack.length - 1];
|
||||
setUndoStack(prev => prev.slice(0, -1));
|
||||
|
||||
console.log(`🎯 准备撤销: ${last}`);
|
||||
// 准备撤销操作
|
||||
|
||||
if (last === 'move' && moveUndoHistory.length > 0) {
|
||||
console.log('↩️ 执行移动撤销');
|
||||
// 执行移动撤销
|
||||
await handleUndoMove();
|
||||
} else if (last === 'delete' && undoHistory.length > 0) {
|
||||
console.log('↩️ 执行删除撤销');
|
||||
// 执行删除撤销
|
||||
await handleUndo();
|
||||
}
|
||||
|
||||
console.log('✅ 撤销完成');
|
||||
// 撤销完成
|
||||
},
|
||||
onCopy: () => {
|
||||
const result = handleCopy();
|
||||
|
||||
@@ -9,6 +9,9 @@ import requestManager, { RequestType } from '../services/requestManager';
|
||||
import domCleanup from '../utils/domCleanup';
|
||||
import ImageWaterfall from './ImageWaterfall';
|
||||
import Dashboard from './Dashboard';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const logger = createLogger('MainContent');
|
||||
|
||||
function MainContent() {
|
||||
const { currentLibraryId } = useLibraryStore();
|
||||
@@ -117,7 +120,7 @@ function MainContent() {
|
||||
if (error.name === 'CanceledError' || error.name === 'AbortError') {
|
||||
return;
|
||||
}
|
||||
console.error('Error loading images:', error);
|
||||
logger.error('加载图片失败:', error.message);
|
||||
requestManager.error(requestContext.id);
|
||||
} finally {
|
||||
// 只有当请求仍然有效时才更新状态
|
||||
@@ -167,7 +170,7 @@ function MainContent() {
|
||||
const { setSelectedFolder } = useImageStore.getState();
|
||||
setSelectedFolder(restoreFolder);
|
||||
localStorage.removeItem('flypic_restore_folder');
|
||||
console.log('✅ 已恢复到文件夹:', restoreFolder);
|
||||
logger.data('恢复文件夹:', restoreFolder);
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -174,7 +174,7 @@ function RightPanel() {
|
||||
filename: actualNewName
|
||||
});
|
||||
|
||||
logger.debug(`✅ 重命名成功: ${oldFilename} → ${actualNewName}`);
|
||||
logger.file(`重命名成功: ${oldFilename} → ${actualNewName}`);
|
||||
} catch (error) {
|
||||
logger.error('重命名失败:', error);
|
||||
alert('重命名失败: ' + (error.message || '未知错误'));
|
||||
@@ -230,7 +230,7 @@ function RightPanel() {
|
||||
const result = await fileAPI.rename(currentLibraryId, oldPath, newName);
|
||||
const newPath = result.newPath;
|
||||
|
||||
logger.debug(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`);
|
||||
logger.file(`文件夹重命名: ${oldName} → ${newName}`);
|
||||
|
||||
const { setFolders, setSelectedFolder: setSelectedFolderGlobal, setSelectedFolderItem } = useImageStore.getState();
|
||||
|
||||
@@ -241,7 +241,7 @@ function RightPanel() {
|
||||
});
|
||||
|
||||
if (isRenamingCurrentFolder) {
|
||||
logger.debug(`📂 重命名当前文件夹: ${oldPath} → ${newPath}`);
|
||||
logger.file(`重命名当前文件夹: ${oldPath} → ${newPath}`);
|
||||
setSelectedFolderGlobal(newPath);
|
||||
|
||||
// 重命名当前浏览的文件夹时,立即刷新该文件夹的图片列表,避免数量显示为 0
|
||||
@@ -256,7 +256,7 @@ function RightPanel() {
|
||||
}
|
||||
|
||||
imageAPI.getFolders(currentLibraryId).then(foldersRes => {
|
||||
logger.debug('📁 重命名后最新文件夹列表:', foldersRes.folders);
|
||||
logger.data('重命名后刷新文件夹列表');
|
||||
setFolders(foldersRes.folders);
|
||||
|
||||
const newFolderItem = foldersRes.folders.find(f => f.path === newPath);
|
||||
@@ -319,7 +319,7 @@ function RightPanel() {
|
||||
setSelectedImages(updatedSelectedImages);
|
||||
}
|
||||
|
||||
logger.debug(`✅ 已更新 ${paths.length} 张图片的评分为 ${newRating} 星`);
|
||||
logger.file(`已更新 ${paths.length} 张图片的评分为 ${newRating} 星`);
|
||||
} catch (error) {
|
||||
logger.error('更新评分失败:', error);
|
||||
alert('更新评分失败: ' + (error.message || '未知错误'));
|
||||
@@ -364,7 +364,7 @@ function RightPanel() {
|
||||
// 对于不支持的格式,只显示缩略图
|
||||
if (!shouldLoadOriginal) {
|
||||
setIsLoadingOriginal(false);
|
||||
logger.debug(`格式 ${imageFormat} 不支持直接显示原图,使用缩略图`);
|
||||
// 不支持直接显示原图,使用缩略图
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -593,7 +593,7 @@ function RightPanel() {
|
||||
// 1. 先写入应用内剪贴板(同步,用于应用内粘贴)
|
||||
const itemsToCopy = [{ type: 'file', path: selectedImage.path, data: selectedImage }];
|
||||
copyToClipboard(itemsToCopy, 'copy');
|
||||
logger.debug(`📋 已复制 1 个文件到应用内剪贴板`);
|
||||
logger.file('已复制 1 个文件到应用内剪贴板');
|
||||
|
||||
// 2. 获取原图URL,写入系统剪贴板
|
||||
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
|
||||
@@ -645,7 +645,7 @@ function RightPanel() {
|
||||
}
|
||||
|
||||
// 方案2:使用 canvas + contenteditable + execCommand(非 HTTPS 环境)
|
||||
logger.debug('尝试 Canvas + execCommand 方案...');
|
||||
// 尝试 Canvas 方案
|
||||
const canvasSuccess = await fallbackCopyImageViaCanvas(imageUrl);
|
||||
if (canvasSuccess) {
|
||||
setImageCopied(true);
|
||||
@@ -654,7 +654,7 @@ function RightPanel() {
|
||||
}
|
||||
|
||||
// 方案3:直接使用图片 URL + contenteditable
|
||||
logger.debug('尝试直接图片 URL 方案...');
|
||||
// 尝试直接 URL 方案
|
||||
const directSuccess = await fallbackCopyImage(imageUrl);
|
||||
if (directSuccess) {
|
||||
setImageCopied(true);
|
||||
@@ -778,7 +778,7 @@ function RightPanel() {
|
||||
// 1. 先写入应用内剪贴板(同步,用于应用内粘贴)
|
||||
const itemsToCopy = imagesToCopy.map(img => ({ type: 'file', path: img.path, data: img }));
|
||||
copyToClipboard(itemsToCopy, 'copy');
|
||||
logger.debug(`📋 已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
|
||||
logger.file(`已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
|
||||
|
||||
if (imagesToCopy.length === 1) {
|
||||
// 单张图片:直接复制
|
||||
@@ -837,7 +837,7 @@ function RightPanel() {
|
||||
}
|
||||
|
||||
// 方案2:使用 contenteditable + execCommand
|
||||
logger.debug('尝试 contenteditable 批量复制方案...');
|
||||
// 尝试批量复制
|
||||
const success = await fallbackCopyMultipleImages(imageUrls);
|
||||
if (success) {
|
||||
setImageCopied(true);
|
||||
@@ -901,7 +901,7 @@ function RightPanel() {
|
||||
const progress = Math.round(((i + 1) / imagesToExport.length) * 90); // 90% 用于下载
|
||||
setExportProgress(progress);
|
||||
|
||||
logger.debug(`已添加: ${img.filename} (${i + 1}/${imagesToExport.length})`);
|
||||
// 已添加到 ZIP
|
||||
} catch (error) {
|
||||
logger.error(`下载失败: ${img.filename}`, error);
|
||||
}
|
||||
@@ -909,7 +909,7 @@ function RightPanel() {
|
||||
|
||||
// 生成 ZIP 文件
|
||||
setExportProgress(95);
|
||||
logger.debug('正在生成 ZIP 文件...');
|
||||
// 生成 ZIP
|
||||
const zipBlob = await zip.generateAsync({
|
||||
type: 'blob',
|
||||
compression: 'DEFLATE',
|
||||
@@ -926,7 +926,7 @@ function RightPanel() {
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(link.href);
|
||||
|
||||
logger.debug('导出完成!');
|
||||
logger.data('导出完成');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('导出失败:', error);
|
||||
@@ -982,7 +982,7 @@ function RightPanel() {
|
||||
const progress = Math.round(((i + 1) / folderImages.length) * 90);
|
||||
setFolderExportProgress(progress);
|
||||
|
||||
logger.debug(`已添加: ${filePath} (${i + 1}/${folderImages.length})`);
|
||||
// 已添加到 ZIP
|
||||
} catch (error) {
|
||||
logger.error(`下载失败: ${img.filename}`, error);
|
||||
}
|
||||
@@ -990,7 +990,7 @@ function RightPanel() {
|
||||
|
||||
// 生成 ZIP 文件
|
||||
setFolderExportProgress(95);
|
||||
logger.debug('正在生成 ZIP 文件...');
|
||||
// 生成 ZIP
|
||||
const zipBlob = await zip.generateAsync({
|
||||
type: 'blob',
|
||||
compression: 'DEFLATE',
|
||||
@@ -1007,7 +1007,7 @@ function RightPanel() {
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(link.href);
|
||||
|
||||
logger.debug('文件夹导出完成!');
|
||||
logger.data('文件夹导出完成');
|
||||
} catch (error) {
|
||||
logger.error('导出文件夹失败:', error);
|
||||
alert('导出文件夹失败,请重试');
|
||||
|
||||
@@ -304,7 +304,7 @@ function Sidebar() {
|
||||
]).then(([deleteResult, foldersRes]) => {
|
||||
const { setFolders } = useImageStore.getState();
|
||||
if (deleteResult.failed.length > 0) {
|
||||
logger.warn(`⚠️ 删除失败:`, deleteResult.failed);
|
||||
logger.warn('删除失败:', deleteResult.failed);
|
||||
// 失败时回滚
|
||||
setUndoHistory(undoHistory);
|
||||
setUndoToast({ isVisible: false, message: '', count: 0 });
|
||||
@@ -359,7 +359,6 @@ function Sidebar() {
|
||||
|
||||
// 4. 立即跳转到恢复的文件夹
|
||||
setSelectedFolder(lastDeleted.folderPath);
|
||||
logger.debug(`📂 跳转到文件夹: ${lastDeleted.folderPath}`);
|
||||
|
||||
// 5. 后台执行API调用(不阻塞UI)
|
||||
Promise.all([
|
||||
@@ -369,7 +368,7 @@ function Sidebar() {
|
||||
const { setFolders } = useImageStore.getState();
|
||||
// 检查恢复结果
|
||||
if (restoreResult.failed.length > 0) {
|
||||
logger.warn(`⚠️ 恢复失败: ${restoreResult.failed.length} 个文件`);
|
||||
logger.warn(`恢复失败: ${restoreResult.failed.length} 个文件`);
|
||||
const errorMsg = restoreResult.failed[0].error || '未知错误';
|
||||
|
||||
// 失败时回滚
|
||||
@@ -489,7 +488,7 @@ function Sidebar() {
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
logger.debug(`✅ 已移动 ${items.length} 个${hasFolders ? '文件夹' : '文件'}到: ${targetFolderPath}`);
|
||||
logger.file(`移动完成: ${items.length}个${hasFolders ? '文件夹' : '文件'} → ${targetFolderPath}`);
|
||||
}
|
||||
|
||||
// 3. 刷新文件夹列表
|
||||
@@ -656,7 +655,7 @@ function Sidebar() {
|
||||
setImages(response.images);
|
||||
}
|
||||
|
||||
logger.debug(`✅ 撤销拖拽移动完成`);
|
||||
logger.file('撤销拖拽移动完成');
|
||||
} catch (error) {
|
||||
logger.error('撤销拖拽移动失败:', error);
|
||||
// 失败时回滚
|
||||
@@ -696,7 +695,7 @@ function Sidebar() {
|
||||
} else {
|
||||
// 2. 移动成功,选中新位置
|
||||
setSelectedFolder(newPath);
|
||||
logger.debug(`✅ 已移动文件夹: ${moveFolderPath} -> ${newPath}`);
|
||||
logger.file(`移动文件夹: ${moveFolderPath} → ${newPath}`);
|
||||
}
|
||||
|
||||
// 3. 刷新文件夹列表
|
||||
@@ -758,14 +757,14 @@ function Sidebar() {
|
||||
const result = await fileAPI.rename(currentLibraryId, oldPath, newName);
|
||||
const newPath = result.newPath;
|
||||
|
||||
logger.debug(`✅ 文件夹重命名成功: ${oldName} → ${newName}, 路径: ${oldPath} → ${newPath}`);
|
||||
logger.file(`文件夹重命名: ${oldName} → ${newName}`);
|
||||
|
||||
const { setFolders, setSelectedFolder: setSelectedFolderGlobal, setSelectedFolderItem } = useImageStore.getState();
|
||||
|
||||
// 1. 如果重命名的是当前选中的文件夹,立即切换到新路径
|
||||
// 这样可以避免先显示全部图片的闪烁
|
||||
if (isRenamingCurrentFolder) {
|
||||
logger.debug(`📂 重命名当前文件夹: ${oldPath} → ${newPath}`);
|
||||
logger.file(`重命名当前文件夹: ${oldPath} → ${newPath}`);
|
||||
setSelectedFolderGlobal(newPath);
|
||||
|
||||
// 重命名当前浏览的文件夹时,立即刷新该文件夹的图片列表,避免连续重命名导致数量显示为 0
|
||||
@@ -781,7 +780,7 @@ function Sidebar() {
|
||||
|
||||
// 2. 后台刷新文件夹列表(不阻塞UI)
|
||||
imageAPI.getFolders(currentLibraryId).then(foldersRes => {
|
||||
logger.debug('📁 重命名后最新文件夹列表:', foldersRes.folders);
|
||||
logger.data('重命名后刷新文件夹列表');
|
||||
setFolders(foldersRes.folders);
|
||||
|
||||
// 3. 用最新数据更新 selectedFolderItem,让右侧详情面板立即显示新名称
|
||||
@@ -847,7 +846,7 @@ function Sidebar() {
|
||||
|
||||
try {
|
||||
// 1. 添加素材库
|
||||
logger.debug('📝 添加素材库...');
|
||||
logger.data('添加素材库...');
|
||||
const response = await libraryAPI.add(newLibraryName.trim(), newLibraryPath.trim());
|
||||
const newLibId = response.id;
|
||||
const hasExistingIndex = response.hasExistingIndex;
|
||||
@@ -865,7 +864,7 @@ function Sidebar() {
|
||||
setIsAdding(false); // 立即释放按钮
|
||||
|
||||
// 3. 切换到新素材库
|
||||
logger.debug('🔄 切换到新素材库...');
|
||||
logger.data('切换到新素材库...');
|
||||
await libraryAPI.setCurrent(newLibId);
|
||||
setCurrentLibrary(newLibId);
|
||||
setSelectedFolder(null);
|
||||
@@ -887,7 +886,7 @@ function Sidebar() {
|
||||
|
||||
// 6. 如果有已有索引,先快速加载数据库中的数据
|
||||
if (hasExistingIndex) {
|
||||
logger.debug('检测到已有索引,先加载现有数据...');
|
||||
logger.data('检测到已有索引,先加载现有数据...');
|
||||
try {
|
||||
const [foldersRes, countRes] = await Promise.all([
|
||||
imageAPI.getFolders(newLibId),
|
||||
@@ -895,27 +894,27 @@ function Sidebar() {
|
||||
]);
|
||||
useImageStore.getState().setFolders(foldersRes.folders);
|
||||
useImageStore.getState().setTotalImageCount(countRes.count);
|
||||
logger.debug('✅ 已加载现有数据');
|
||||
logger.data('已加载现有数据');
|
||||
} catch (err) {
|
||||
logger.warn('⚠️ 加载现有数据失败:', err);
|
||||
logger.warn('加载现有数据失败:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 7. 开始异步扫描(不等待,Socket.IO 会推送进度)
|
||||
logger.debug('🔍 开始异步扫描...');
|
||||
logger.data('开始异步扫描...');
|
||||
if (hasExistingIndex) {
|
||||
logger.debug('执行增量同步,检测变化...');
|
||||
logger.data('执行增量同步,检测变化...');
|
||||
scanAPI.sync(newLibId, false); // wait=false,异步执行
|
||||
} else {
|
||||
logger.debug('首次添加,执行全量扫描...');
|
||||
logger.data('首次添加,执行全量扫描...');
|
||||
scanAPI.fullScan(newLibId, false); // wait=false,异步执行
|
||||
}
|
||||
|
||||
// 扫描在后台进行,Socket.IO 会推送进度和完成事件
|
||||
// App.jsx 中的 scanComplete 监听器会自动刷新数据
|
||||
logger.debug('✅ 扫描已启动,请等待进度显示...');
|
||||
logger.data('扫描已启动,请等待进度显示...');
|
||||
} catch (error) {
|
||||
logger.error('❌ Error adding library:', error);
|
||||
logger.error('添加素材库失败:', error);
|
||||
|
||||
// 提取错误信息
|
||||
let errorMessage = error.message || '未知错误';
|
||||
@@ -1008,7 +1007,7 @@ function Sidebar() {
|
||||
}
|
||||
}).catch(() => { });
|
||||
} catch (error) {
|
||||
logger.error('Error setting current library:', error);
|
||||
logger.error('切换素材库失败:', error);
|
||||
alert('切换素材库失败: ' + error.message);
|
||||
useImageStore.getState().setImageLoadingState({ isLoading: false });
|
||||
} finally {
|
||||
|
||||
@@ -141,12 +141,12 @@ export const useImageClipboard = (showConflictDialog) => {
|
||||
// 1. 立即写入应用内剪贴板(用于应用内粘贴,同步操作)
|
||||
const itemsToCopy = imagesToCopy.map(img => ({ type: 'file', path: img.path, data: img }));
|
||||
copyToClipboard(itemsToCopy, 'copy');
|
||||
logger.debug(`📋 已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
|
||||
logger.file(`已复制 ${itemsToCopy.length} 个文件到应用内剪贴板`);
|
||||
|
||||
// 2. 异步写入系统剪贴板(用于跨应用粘贴,不阻塞)
|
||||
copyImagesToSystemClipboard(imagesToCopy).then(success => {
|
||||
if (success) {
|
||||
logger.debug(`✅ 已写入系统剪贴板,可粘贴到外部应用`);
|
||||
logger.file('已写入系统剪贴板,可粘贴到外部应用');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -184,7 +184,7 @@ export const useImageClipboard = (showConflictDialog) => {
|
||||
const executePaste = useCallback(async (items, targetFolder, conflictAction) => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
logger.debug(`📋 开始粘贴 ${items.length} 个文件到: ${targetFolder}`);
|
||||
logger.file(`开始粘贴 ${items.length} 个文件到: ${targetFolder}`);
|
||||
|
||||
// 1. 立即更新文件夹计数(乐观更新)
|
||||
const originalFolders = folders;
|
||||
|
||||
@@ -152,7 +152,7 @@ export const useImageDelete = () => {
|
||||
if (restoredFolder && restoredFolder !== selectedFolder) {
|
||||
// 跨文件夹:先跳转,让文件夹加载自然显示图片
|
||||
useImageStore.getState().setSelectedFolder(restoredFolder);
|
||||
logger.debug(`📂 跳转到文件夹: ${restoredFolder}`);
|
||||
// 跳转到恢复的文件夹
|
||||
} else {
|
||||
// 同文件夹:立即添加到列表
|
||||
const restoredImages = [...images, ...lastDeleted.images];
|
||||
|
||||
@@ -78,7 +78,7 @@ export const useImageMove = (showConflictDialog) => {
|
||||
const executeMove = useCallback(async (items, targetFolder, conflictAction = 'rename') => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
logger.debug(`📁 开始移动 ${items.length} 个文件到: ${targetFolder}`);
|
||||
logger.file(`开始移动 ${items.length} 个文件到: ${targetFolder}`);
|
||||
|
||||
// 1. 立即从当前列表中移除这些图片(乐观更新)
|
||||
const movedPaths = new Set(items.map(item => item.path));
|
||||
@@ -164,7 +164,7 @@ export const useImageMove = (showConflictDialog) => {
|
||||
setImages(response.images);
|
||||
}
|
||||
|
||||
logger.debug(`✅ 移动完成: 成功 ${successCount} 个${failedCount > 0 ? `, 失败 ${failedCount} 个` : ''}`);
|
||||
logger.file(`移动完成: 成功 ${successCount} 个${failedCount > 0 ? `, 失败 ${failedCount} 个` : ''}`);
|
||||
|
||||
return { success: true, successCount, failedCount };
|
||||
} catch (error) {
|
||||
@@ -305,7 +305,7 @@ export const useImageMove = (showConflictDialog) => {
|
||||
setImages(response.images);
|
||||
}
|
||||
|
||||
logger.debug(`✅ 撤销移动完成`);
|
||||
logger.file('撤销移动完成');
|
||||
}).catch(error => {
|
||||
logger.error('撤销移动失败:', error);
|
||||
// 失败时回滚
|
||||
|
||||
@@ -76,7 +76,7 @@ export const useImageRating = () => {
|
||||
useImageStore.getState().setOriginalImages(response.images);
|
||||
}
|
||||
|
||||
logger.debug(`⭐ 已将 ${imagesToRate.length} 张图片评为 ${rating} 星`);
|
||||
logger.file(`已将 ${imagesToRate.length} 张图片评为 ${rating} 星`);
|
||||
} catch (error) {
|
||||
logger.error('评分失败:', error);
|
||||
alert('评分失败: ' + (error.message || '未知错误'));
|
||||
|
||||
@@ -72,7 +72,7 @@ export const useImageRename = () => {
|
||||
filename: actualNewName
|
||||
});
|
||||
|
||||
logger.debug(`✅ 重命名成功: ${oldFilename} → ${actualNewName}`);
|
||||
logger.file(`重命名成功: ${oldFilename} → ${actualNewName}`);
|
||||
} catch (error) {
|
||||
logger.error('重命名失败:', error);
|
||||
alert('重命名失败: ' + (error.message || '未知错误'));
|
||||
|
||||
@@ -98,7 +98,7 @@ export const useImageUpload = () => {
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length === 0) return;
|
||||
|
||||
logger.debug(`📤 准备上传 ${files.length} 个文件到: ${selectedFolder || '根目录'}`);
|
||||
logger.file(`准备上传 ${files.length} 个文件到: ${selectedFolder || '根目录'}`);
|
||||
|
||||
// 开始上传
|
||||
setUploadProgress({ isUploading: true, percent: 0, current: 0, total: files.length });
|
||||
@@ -121,7 +121,7 @@ export const useImageUpload = () => {
|
||||
const conflicts = result.conflicts || [];
|
||||
if (conflicts.length > 0 && onConflict) {
|
||||
// 有冲突,回调处理
|
||||
logger.debug(`⚠️ 检测到 ${conflicts.length} 个文件冲突`);
|
||||
logger.file(`检测到 ${conflicts.length} 个文件冲突`);
|
||||
onConflict(conflicts, files, selectedFolder || '');
|
||||
setUploadProgress({ isUploading: false, percent: 0, current: 0, total: 0 });
|
||||
return { hasConflicts: true, conflicts };
|
||||
@@ -146,7 +146,7 @@ export const useImageUpload = () => {
|
||||
try {
|
||||
const response2 = await imageAPI.search(currentLibraryId, params);
|
||||
setImages(response2.images);
|
||||
logger.debug('✅ 缩略图刷新完成');
|
||||
logger.data('缩略图刷新完成');
|
||||
} catch (err) {
|
||||
logger.error('刷新缩略图失败:', err);
|
||||
}
|
||||
@@ -176,10 +176,10 @@ export const useImageUpload = () => {
|
||||
const uploadWithConflictAction = useCallback(async (files, targetFolder, conflictAction) => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
logger.debug(`处理上传冲突: ${conflictAction}`);
|
||||
logger.file(`处理上传冲突: ${conflictAction}`);
|
||||
|
||||
if (conflictAction === 'skip') {
|
||||
logger.debug('用户选择跳过上传');
|
||||
logger.file('用户选择跳过上传');
|
||||
return { success: true, skipped: true };
|
||||
}
|
||||
|
||||
@@ -223,7 +223,7 @@ export const useImageUpload = () => {
|
||||
try {
|
||||
const response2 = await imageAPI.search(currentLibraryId, params);
|
||||
setImages(response2.images);
|
||||
logger.debug('✅ 缩略图刷新完成');
|
||||
logger.data('缩略图刷新完成');
|
||||
} catch (err) {
|
||||
logger.error('刷新缩略图失败:', err);
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ export const useInfiniteScroll = () => {
|
||||
if (error.name === 'CanceledError' || error.name === 'AbortError') {
|
||||
return;
|
||||
}
|
||||
logger.error('Error loading more images:', error);
|
||||
logger.error('加载更多图片失败:', error.message);
|
||||
requestManager.error(requestContext.id);
|
||||
setImageLoadingState({ isLoading: false });
|
||||
}
|
||||
|
||||
+100
-39
@@ -1,11 +1,27 @@
|
||||
/**
|
||||
* 统一日志管理工具
|
||||
* 生产环境自动禁用调试日志
|
||||
* FlyPic 前端日志系统
|
||||
* 专注于用户操作和UI交互日志
|
||||
*
|
||||
* 日志分类:
|
||||
* - USER: 用户操作(点击、选择、快捷键)
|
||||
* - FILE: 文件操作(复制、移动、删除、重命名)
|
||||
* - DATA: 数据加载(加载图片、文件夹、搜索)
|
||||
* - UI: UI状态(主题切换、面板展开)
|
||||
* - ERROR: 错误(API失败、操作异常)
|
||||
*/
|
||||
|
||||
const isDev = import.meta.env.DEV;
|
||||
const isDebugEnabled = isDev || import.meta.env.VITE_ENABLE_DEBUG === 'true';
|
||||
|
||||
// 日志类别配置
|
||||
const LOG_CATEGORIES = {
|
||||
USER: { emoji: '👤', color: '#3b82f6', label: 'USER' }, // 用户操作
|
||||
FILE: { emoji: '📁', color: '#10b981', label: 'FILE' }, // 文件操作
|
||||
DATA: { emoji: '📊', color: '#8b5cf6', label: 'DATA' }, // 数据加载
|
||||
UI: { emoji: '🎨', color: '#f59e0b', label: 'UI' }, // UI状态
|
||||
ERROR: { emoji: '❌', color: '#ef4444', label: 'ERROR' }, // 错误
|
||||
};
|
||||
|
||||
/**
|
||||
* 日志工具类
|
||||
*/
|
||||
@@ -17,44 +33,96 @@ class Logger {
|
||||
/**
|
||||
* 格式化日志前缀
|
||||
*/
|
||||
_getPrefix() {
|
||||
return this.namespace ? `[${this.namespace}]` : '';
|
||||
_getPrefix(category) {
|
||||
const config = LOG_CATEGORIES[category] || {};
|
||||
const emoji = config.emoji || '📝';
|
||||
const label = config.label || 'LOG';
|
||||
const ns = this.namespace ? `[${this.namespace}]` : '';
|
||||
return `${emoji} ${label}${ns}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调试日志(仅开发环境)
|
||||
* 输出彩色日志
|
||||
*/
|
||||
debug(...args) {
|
||||
if (isDebugEnabled) {
|
||||
console.log(this._getPrefix(), ...args);
|
||||
_log(category, method, ...args) {
|
||||
if (!isDebugEnabled && category !== 'ERROR') return;
|
||||
|
||||
const config = LOG_CATEGORIES[category];
|
||||
const prefix = this._getPrefix(category);
|
||||
|
||||
if (config && config.color) {
|
||||
console[method](
|
||||
`%c${prefix}`,
|
||||
`color: ${config.color}; font-weight: bold;`,
|
||||
...args
|
||||
);
|
||||
} else {
|
||||
console[method](prefix, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 用户操作日志 ====================
|
||||
|
||||
/**
|
||||
* 信息日志(仅开发环境)
|
||||
* 用户操作日志
|
||||
* @example logger.user('点击图片', imageId)
|
||||
*/
|
||||
info(...args) {
|
||||
if (isDebugEnabled) {
|
||||
console.info(this._getPrefix(), ...args);
|
||||
}
|
||||
user(...args) {
|
||||
this._log('USER', 'log', ...args);
|
||||
}
|
||||
|
||||
// ==================== 文件操作日志 ====================
|
||||
|
||||
/**
|
||||
* 文件操作日志
|
||||
* @example logger.file('删除文件', { count: 3, folder: '/photos' })
|
||||
*/
|
||||
file(...args) {
|
||||
this._log('FILE', 'log', ...args);
|
||||
}
|
||||
|
||||
// ==================== 数据加载日志 ====================
|
||||
|
||||
/**
|
||||
* 数据加载日志
|
||||
* @example logger.data('加载图片', { count: 100, time: 500 })
|
||||
*/
|
||||
data(...args) {
|
||||
this._log('DATA', 'log', ...args);
|
||||
}
|
||||
|
||||
// ==================== UI状态日志 ====================
|
||||
|
||||
/**
|
||||
* UI状态日志
|
||||
* @example logger.ui('切换主题', 'dark')
|
||||
*/
|
||||
ui(...args) {
|
||||
this._log('UI', 'log', ...args);
|
||||
}
|
||||
|
||||
// ==================== 错误日志 ====================
|
||||
|
||||
/**
|
||||
* 错误日志(所有环境)
|
||||
* @example logger.error('API请求失败', error)
|
||||
*/
|
||||
error(...args) {
|
||||
this._log('ERROR', 'error', ...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 警告日志(所有环境)
|
||||
*/
|
||||
warn(...args) {
|
||||
console.warn(this._getPrefix(), ...args);
|
||||
if (!isDebugEnabled) return;
|
||||
console.warn(this._getPrefix(''), ...args);
|
||||
}
|
||||
|
||||
// ==================== 调试工具 ====================
|
||||
|
||||
/**
|
||||
* 错误日志(所有环境)
|
||||
*/
|
||||
error(...args) {
|
||||
console.error(this._getPrefix(), ...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 表格日志(仅开发环境)
|
||||
* 表格输出(仅开发环境)
|
||||
*/
|
||||
table(data) {
|
||||
if (isDebugEnabled) {
|
||||
@@ -68,9 +136,9 @@ class Logger {
|
||||
group(label, collapsed = false) {
|
||||
if (isDebugEnabled) {
|
||||
if (collapsed) {
|
||||
console.groupCollapsed(this._getPrefix(), label);
|
||||
console.groupCollapsed(label);
|
||||
} else {
|
||||
console.group(this._getPrefix(), label);
|
||||
console.group(label);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,20 +150,17 @@ class Logger {
|
||||
}
|
||||
|
||||
/**
|
||||
* 性能计时开始
|
||||
* 性能计时
|
||||
*/
|
||||
time(label) {
|
||||
if (isDebugEnabled) {
|
||||
console.time(this._getPrefix() + ' ' + label);
|
||||
console.time(label);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 性能计时结束
|
||||
*/
|
||||
timeEnd(label) {
|
||||
if (isDebugEnabled) {
|
||||
console.timeEnd(this._getPrefix() + ' ' + label);
|
||||
console.timeEnd(label);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,22 +169,18 @@ class Logger {
|
||||
* 创建带命名空间的日志器
|
||||
* @param {string} namespace - 日志命名空间
|
||||
* @returns {Logger} 日志器实例
|
||||
*
|
||||
* @example
|
||||
* const logger = createLogger('ImageWaterfall')
|
||||
* logger.user('选中图片', imageId)
|
||||
*/
|
||||
export function createLogger(namespace) {
|
||||
return new Logger(namespace);
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认日志器(无命名空间)
|
||||
* 默认日志器
|
||||
*/
|
||||
export const logger = new Logger();
|
||||
|
||||
/**
|
||||
* 快捷方法(无命名空间)
|
||||
*/
|
||||
export const log = (...args) => logger.debug(...args);
|
||||
export const info = (...args) => logger.info(...args);
|
||||
export const warn = (...args) => logger.warn(...args);
|
||||
export const error = (...args) => logger.error(...args);
|
||||
|
||||
export default logger;
|
||||
Reference in new issue
Block a user