/** * 日志管理工具 * 解决微信小程序真机调试时的日志文件访问问题 */ /** * 初始化日志文件系统 * 在应用启动时调用,确保日志文件存在 */ export function initLogFiles() { // #ifdef MP-WEIXIN try { const fs = wx.getFileSystemManager(); const logDirPath = `${wx.env.USER_DATA_PATH}/miniprogramLog`; const logFiles = ['log1', 'log2', 'log3']; // 检查并创建日志文件的函数 function checkAndCreateFiles() { logFiles.forEach(fileName => { const filePath = `${logDirPath}/${fileName}`; fs.access({ path: filePath, success: () => { console.log(`Log file ${fileName} exists`); }, fail: () => { console.log(`Log file ${fileName} does not exist, creating it`); fs.writeFile({ filePath: filePath, data: '', success: () => { console.log(`Log file ${fileName} created successfully`); }, fail: err => { console.error(`Failed to create log file ${fileName}`, err); } }); } }); }); } // 创建目录 fs.access({ path: logDirPath, success: () => { console.log('Log directory exists'); checkAndCreateFiles(); }, fail: () => { console.log('Log directory does not exist, creating it'); fs.mkdir({ dirPath: logDirPath, success: () => { console.log('Log directory created successfully'); checkAndCreateFiles(); }, fail: err => { console.error('Failed to create log directory', err); } }); } }); } catch (error) { console.error('Failed to initialize log files:', error); } // #endif } /** * 安全的日志写入 * @param {string} message - 日志消息 * @param {string} level - 日志级别 (info, warn, error) */ export function writeLog(message, level = 'info') { // #ifdef MP-WEIXIN try { const fs = wx.getFileSystemManager(); const logDirPath = `${wx.env.USER_DATA_PATH}/miniprogramLog`; const timestamp = new Date().toISOString(); const logEntry = `[${timestamp}] [${level.toUpperCase()}] ${message}\n`; fs.appendFile({ filePath: `${logDirPath}/log1`, data: logEntry, success: () => { // 日志写入成功 }, fail: err => { console.error('Failed to write log:', err); } }); } catch (error) { console.error('Failed to write log:', error); } // #endif } /** * 清理旧日志文件 */ export function cleanOldLogs() { // #ifdef MP-WEIXIN try { const fs = wx.getFileSystemManager(); const logDirPath = `${wx.env.USER_DATA_PATH}/miniprogramLog`; fs.readdir({ dirPath: logDirPath, success: (res) => { const files = res.files; const now = Date.now(); const maxAge = 7 * 24 * 60 * 60 * 1000; // 7天 files.forEach(fileName => { const filePath = `${logDirPath}/${fileName}`; fs.stat({ path: filePath, success: (statRes) => { if (now - statRes.stats.lastAccessedTime > maxAge) { fs.unlink({ filePath: filePath, success: () => { console.log(`Deleted old log file: ${fileName}`); }, fail: err => { console.error(`Failed to delete old log file: ${fileName}`, err); } }); } } }); }); }, fail: err => { console.error('Failed to read log directory:', err); } }); } catch (error) { console.error('Failed to clean old logs:', error); } // #endif }