electron-log

repository·master·Indexed 23 days ago

https://github.com/megahertz/electron-log

A simple, dependency-free logging module for Electron, Node.js, and NW.js applications. It supports logging across Main, Renderer, and Preload processes with multiple transports including console, file, IPC, and remote. Key features include an errorHandler to catch unhandled errors and promise rejections, an eventLogger for capturing Electron lifecycle and process events, and the ability to spy on renderer console.log calls.

Tokens
11K
Snippets
22
Records
75
Agent score
79%

What's inside electron-log

  1. How to log Electron events using eventLogger

    master

    The eventLogger allows you to automatically capture and save critical Electron lifecycle and process events (like crashes or load failures) to your log files.

    By default, it tracks:

    • app events: certificate-error, child-process-gone, render-process-gone.
    • webContents events: crashed, gpu-process-crashed.
    • Every WebContents event: did-fail-load, did-fail-provisional-load, plugin-crashed, preload-error.

    You can control which events are captured, how they are formatted, and at what log level they are recorded using the log.eventLogger API.

  2. Customize the log file path with `resolvePathFn`

    master

    You can control where log files are stored by providing a custom resolvePathFn. This function receives a variables object of type PathVariables.

    To use the default Electron logs directory (app.getPath('logs')), use the following implementation:

    log.transports.file.resolvePathFn = (variables) => {
      return path.join(variables.electronDefaultDir, variables.fileName);
    }

    Note: The directory hierarchy will be created automatically if it does not exist.

  3. Catch unhandled errors and rejections with log.errorHandler

    master

    You can use electron-log to automatically collect all unhandled errors and promise rejections. To enable this, call log.errorHandler.startCatching().

    To collect logs from both the Main and Renderer processes, you must call startCatching() in both environments.

    Available methods:

    • log.errorHandler.startCatching(options?): Starts the error catching mechanism.
    • log.errorHandler.stopCatching(): Stops the error catching mechanism.
    • log.errorHandler.handle(error, options?): Manually processes an error. This works even if catching hasn't been explicitly started.
  4. Migrate from v4 to v5

    master

    Upgrading to v5 requires Node.js 14+ or Electron 13+. Due to renderer process restrictions, logging logic must now be moved to the main process. The logger must be initialized in the main process before any windows are created to enable IPC communication with renderer processes.

    Installation

    npm install electron-log@5

    Implementation Pattern

    1. In the Main Process: Import from electron-log/main and call log.initialize().
    2. In the Renderer Process: Import from electron-log/renderer and use as normal.
    // main.js
    import log from 'electron-log/main';
    
    // It preloads electron-log IPC code in renderer processes
    log.initialize();
    // renderer.ts
    import log from 'electron-log/renderer';
    
    log.info('Log from the renderer');
  5. Use Remote transport to send logs via HTTP POST

    master

    The Remote transport allows you to send log messages from the main process to a specified URL via a JSON POST request. Each request contains a LogMessage body including the log level, date, client information, and the log data itself.

    To use it, configure the url and the minimum level required for a message to be sent via this transport.

    log.transports.remote.level = 'warn';
    log.transports.remote.url = 'https://example.com/myapp/add-log'
    log.warn('Some problem appears', { error: e });
  6. Migrate from v3 to v4

    master

    Upgrading to v4 involves changes to default log paths and file transport configuration.

    Default Log Path Changes

    On Linux and Windows, the default log path was changed to be more compatible with Electron's app.getPath('logs').

    • Linux: ~/.config/{app name}/logs/{process type}.log
    • Windows: %USERPROFILE%\AppData\Roaming\{app name}\logs\{process type}.log

    To maintain old file paths, override file.resolvePath.

    File Transport Updates

    • file.fileName now dynamically resolves to main.log, renderer.log, or worker.log based on the process type.
    • A new method file.getFile() is available to manipulate the current log file.

    Deprecations (Removed in v5)

    If you are on v4, be aware that the following options/methods are deprecated and will be removed in v5:

    • file.file (use file.resolvePath instead)
    • file.bytesWritten (use file.getFile().bytesWritten instead)
    • file.fileSize (use file.getFile().size instead)
    • file.clear() (use file.getFile().clear() instead)
    • file.findLogPath() (use file.getFile().path instead)
    • file.init()
    // Example: Overriding default log path in v4
    log.transports.file.resolvePath = (variables) => {
      return path.join(variables.libraryDefaultDir, variables.fileName);
    }
  7. Initialize the logger in a renderer process (Standard Bundler Setup)

    master

    In electron-log v5+, renderer loggers act as collectors that send data to the main process via IPC. For the most common setup (using a bundler with contextIsolation and sandbox enabled), you must initialize the logger in the main process and import the renderer module in your renderer process.

    1. In your main process code, call log.initialize().
    2. In your renderer process code, import electron-log/renderer to use the logger.

    This method automatically injects a built-in preload script into the default session and any sessions created after initialization.

    // main.js
    import log from 'electron-log/main';
    log.initialize();
    
    // renderer.ts
    import log from 'electron-log/renderer';
    log.info('Log from the renderer');
  8. Migrate from v2 to v3

    master

    Upgrading to v3 introduces changes to process configuration and default settings.

    Key Changes

    • Separate Configuration: Each process (main and renderer) is configured separately. Changes must be applied to both processes.
    • Imports: Requiring electron-log/main and electron-log/renderer is deprecated.
    • Default Log Level: transports.file.level now defaults to 'silly'.
    • Stream Configuration: transports.file.stream and streamConfig have been removed. Use file, fileName, or writeOptions instead.
    • Packaged Apps: rendererConsole and mainConsole transports are disabled by default in packaged applications.
  9. Workaround for using electron-log with esbuild ESM

    master

    When using esbuild to bundle for ESM, you may encounter issues requiring a workaround to enable require functionality. You can resolve this by adding a banner to your esbuild configuration that injects createRequire from the module package. This allows the ESM bundle to use require via import.meta.url.

    const esBuildOptions = {
      banner: {
        js:
          'import { createRequire } from \'module\';\n'
          + 'const require = createRequire(import.meta.url);',
      },
      ...
    };