electron之【前端如何留存日志文件?】

44 阅读1分钟

测试的时候、生产环境的时候出现问题需要排查确认,后端同学会说:"日志发过来看看",我们前端大部分是没有本地日志文件的,只能说:"我打开控制台,你下次复现了叫我~",这样做面临的问题:容易背黑锅、显得不专业。

本文主要是记录前端怎么把代码中的console.log等信息也写到本地日志文件中,希望能够帮助到前端小伙伴们~

话不多说,直接上代码(直接cv到electron的main.js即可用)

// 1. 引入需要的文件
const { app: electronApp } = require('electron');
const path = require('path')
const logDir = path.join(path.dirname(electronApp.getPath('exe')), 'logs'); // 这里是获取到安装目录,在下面创建logs
const logFile = path.join(logDir, 'renderer.log');
// 2. 创建目录
require('fs').mkdirSync(logDir, { recursive: true });
electronApp.commandLine.appendSwitch('disable-features', 'LogConsoleSourceLocation');
// 3. 启用文件日志并设定级别
electronApp.commandLine.appendSwitch('enable-logging');          // 打开日志通道
electronApp.commandLine.appendSwitch('log-level', '1');          // 0=info,1=warning,2=error…
electronApp.commandLine.appendSwitch('v', '0');                  // 详细级别(0~3 即可)
electronApp.commandLine.appendSwitch('log-file', logFile);       // 落到指定文件

成果展示⬇ 日志文件.png

注意事项‼️ 一定要写到main.js最最最上面,否则可能不生效!