megahertz / electron-log

Simple logging module Electron/Node.js/NW.js application. No dependencies. No complicated configuration.
MIT License
1.27k stars 124 forks source link

Logging to file from renderer does not work #375

Closed melihcoban closed 7 months ago

melihcoban commented 7 months ago

This is my electron webPreferences:

    webPreferences: {
      preload,
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: false,
    },

I initialize the electron-log in main process.

  import log from 'electron-log/main'

  log.initialize({ preload: true });

  log.transports.file.resolvePathFn = () => path.join(__dirname, 'logs/main.log');

Logging works just fine in the main process. However, when I try to log from renderer process (React), I can see the log in the console, but it is not written to a file.

Console:

11:18:33.054 > Testing

Example Code:

import log from 'electron-log/renderer'

const handleClick = () => {
   ...do business
   log.info("Testing");
}

I tried to log from preload.ts as well. I created a context bridge for logging.

contextBridge.exposeInMainWorld('logger', {
  logInfo: (message: string) => {
    log.info(message);
  },
  logCritical: (message: string) => {
    log.warn(message);
  },
  logDebug: (message: string) => {
    log.debug(message);
  },
});

However, this does not log to file as well. In the preload file do I need to import the electron-log/main or electron-log/renderer? What could be the issue here?

EDIT: Importing 'electron-log/main' from both main and preload file gives error Attempted to register a second handler for '__ELECTRON_LOG__' while application is packaged. Importing renderer in preload does not log messages.

melihcoban commented 7 months ago

I set log.transports.file.level = "info" in another file long before, that was why debug message were not written to the file. My bad, sorry!

FlyBooks commented 3 months ago

Hello, could you please tell me how to fix this error (Attempted to register a second handler for '__ELECTRON_LOG__')?