UNPKG

mixone

Version:

MixOne is a Node scaffolding tool implemented based on Vite, used for compiling HTML5, JavasCript, Vue, React and other codes. It supports packaging Web applications with multiple HTML entry points (BS architecture) and desktop installation packages (CS a

91 lines (80 loc) 3.25 kB
const fs = require('fs'); const path = require('path'); const os = require('os'); // 安全地导入electron,避免在非Electron环境中出错 let app; try { app = require('electron').app; } catch (error) { app = null; } /** * 写入日志到指定文件 * @param {string|number} content - 要追加的日志内容 * @param {string} logPath - 日志文件保存路径(可选) * @param {object} options - 其他选项(可选) * @param {boolean} options.clearLogDir - 是否在追加日志前先删除日志目录(默认false) */ function writeLog(content, logPath, options = {}) { try { // 默认日志路径 - 支持非Electron环境 let defaultLogPath; if (app && typeof app.getPath === 'function') { // Electron环境 defaultLogPath = path.join(app.getPath('userData'), 'logs', 'main_process.log'); } else { // 非Electron环境,使用系统临时目录或用户目录 const userDir = os.homedir(); defaultLogPath = path.join(userDir, '.electron-logs', 'main_process.log'); } const finalLogPath = logPath || defaultLogPath; // 处理日志目录 const logDir = path.dirname(finalLogPath); // 如果设置了clearLogDir选项,先删除日志目录 if (options.clearLogDir && fs.existsSync(logDir)) { fs.rmSync(logDir, { recursive: true, force: true }); } // 确保日志目录存在 if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir, { recursive: true }); } // 格式化日志内容 const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); const timestamp = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; const logEntry = `【${timestamp}${content}\n`; // 追加写入日志文件 fs.appendFileSync(finalLogPath, logEntry, 'utf8'); // 输出调试信息,帮助用户了解日志位置 console.log(`日志已写入: ${finalLogPath}`); return true; } catch (error) { console.error('写入日志失败:', error); console.error('尝试写入的路径:', logPath || '默认路径'); console.error('Electron环境:', app ? '是' : '否'); return false; } } /** * 测试日志功能 * @param {string} testContent - 测试内容(可选) */ function testLog(testContent = '测试日志功能') { console.log('开始测试日志功能...'); const result = writeLog(testContent); if (result) { console.log('✅ 日志功能测试成功'); } else { console.log('❌ 日志功能测试失败'); } return result; } module.exports = { writeLog, testLog };