日志优化

This commit is contained in:
Chen committed 2025-12-07 17:12:29 +08:00
1 parent fa5bb66d14
commit aeb403f3c0
21 files changed
+402 -209

No files matched your search

+1
View File
@@ -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();
+34 -35
View File
@@ -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}`);
}
}
}
+5 -5
View File
@@ -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
View File
@@ -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;