You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Electron主进程中用electron-log捕获所有console.log日志?

Redirecting All console.log to electron-log in Electron Main Process Without Manual Replacement

Absolutely! You don’t need to slog through every line of code replacing console.log with log.error or other methods. You can easily intercept and redirect all native console output to electron-log (or similar logging tools) with a few lines of code in your main process. Here’s how to do it:

Step 1: Install electron-log

First, add the package to your project:

npm install electron-log
# Or using yarn
yarn add electron-log

Step 2: Override Native Console Methods

In your main process entry file (typically main.js or main.ts), import electron-log and overwrite the default console methods to map to the corresponding log levels in electron-log. Place this code as early as possible in your main process setup to ensure all subsequent console calls are intercepted:

const log = require('electron-log');

// Map native console methods to electron-log levels
console.log = (...args) => log.info(...args);
console.error = (...args) => log.error(...args);
console.warn = (...args) => log.warn(...args);
console.debug = (...args) => log.debug(...args);
console.trace = (...args) => log.silly(...args); // You can also map to log.trace if preferred

How It Works

  • Any existing console.log('this error', error) call in your code will automatically be routed to log.info('this error', error)
  • If you already have explicit log.error('this error:', error) calls, they’ll continue to work normally—no conflicts here
  • All logs will be persisted to files (by default in Electron’s app data directory), which you can access even after the app is packaged

Optional: Configure electron-log

Tweak the logging behavior to fit your needs, like setting log levels, file size limits, or custom formatting:

// Example configuration
log.transports.file.level = 'info'; // Log all info-level and above messages to file
log.transports.file.maxSize = 5 * 1024 * 1024; // Limit each log file to 5MB
log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}'; // Custom log format

Key Notes

  • Make sure this override code runs before any other code that uses console in the main process—otherwise, early logs might slip through
  • For renderer processes, you’d need a similar setup (or use IPC to send logs to the main process), but this solution focuses solely on the main process as per your question

内容的提问来源于stack exchange,提问作者howMuchCheeseIsTooMuchCheese

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:33:32