前言
Electron打包后为了方便查看日志,我们需要把日志输出到文件中,方便排查。
日志的处理主要在node进程,渲染进程的日志可以通过ipc发送。
自己封装
/assets/node_utils/zlog.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| const { app } = require("electron"); const fs = require("fs"); const path = require("path");
const todayStr = new Date().toISOString().split("T")[0]; const logPath = path.join( app.getPath("userData"), "logs", `log_${todayStr}.log` ); const dirPath = path.dirname(logPath);
if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath, { recursive: true }); }
function log(message, level = "INFO") { const timestamp = new Date().toISOString(); const logEntry = `[${timestamp}] [${level}] ${message}\n`;
fs.appendFile(logPath, logEntry, (err) => { if (err) { console.error("无法写入日志文件:", err); } });
console.log(logEntry.trim()); }
function info(message) { log(message, "INFO"); }
function error(message) { log(message, "ERROR"); }
exports.logger = { info, error, };
|
使用
1 2 3 4
| const { logger } = require("./assets/node_utils/zlog.js");
logger.info("应用启动"); logger.error("发生错误:网络请求失败");
|
日志文件路径
C:\Users\DELL\AppData\Roaming\crawler_qcc_client\app.log
使用winston
winston是一个功能丰富的第三方日志库,支持多传输方式和日志级别。
安装依赖
工具类
/assets/node_utils/zlog.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| const { app } = require("electron"); const winston = require("winston"); const path = require("path"); const fs = require("fs");
const todayStr = new Date().toISOString().split("T")[0]; const logPath = path.join( app.getPath("userData"), "logs", `log_${todayStr}.log` ); const dirPath = path.dirname(logPath);
if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath, { recursive: true }); }
const logger = winston.createLogger({ level: "info", format: winston.format.combine( winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), winston.format.printf(({ timestamp, level, message }) => { return `[${timestamp}] [${level}] ${message}`; }) ), transports: [ new winston.transports.File({ filename: logPath }), new winston.transports.Console(), ], });
exports.logger = logger;
|
使用
1 2 3 4
| const { logger } = require("./assets/node_utils/zlog.js");
logger.info("应用启动"); logger.error("发生错误:网络请求失败");
|
日志文件路径
C:\Users\DELL\AppData\Roaming\crawler_qcc_client\app.log
IPC
主进程
1 2 3 4 5 6
| const { logger } = require("./assets/node_utils/zlog.js"); const { ipcMain } = require("electron");
ipcMain.on("logInfo", (event, arg) => { logger.info(arg); });
|
渲染进程
1 2
| const { ipcRenderer } = window.require("electron"); ipcRenderer.send("logInfo", "页面加载完成");
|