0

Is there way to handle console.log messages from renderer in main process? Similar to CefDisplayHandler::OnConsoleMessage handler in Cef.

Evgeny
  • 274
  • 3
  • 8

2 Answers2

1

You can do this in three ways,

  • Set the enviroment variableELECTRON_ENABLE_LOGGING=true to parse every console.log to your CLI
  • Do a IPCrenderer message to IPCmain, which the logs it for you
  • Add a function to app from the main process

    # MAIN
    const {app} = require('electron')
    app.MySuperCoolLoggingUtility = function (msg) { 
        console.log(msg) 
    }
    
    # RENDERER
    require('electron').remote.app.MySuperCoolLoggingUtility('hi')
    

There are also some ways to limit the log level for specific files via --vmodule= but it is not close to the handler of normal Cef. So you will probably build your own utility function for it.

Hans Koch
  • 4,283
  • 22
  • 33
  • Woha, didn't know about `ELECTRON_ENABLE_LOGGING`. I don't know why I always forget or don't think of going through documentation more thoroughly, so that I know these things from the source, instead of discovering them on the Internet. Nevertheless, upvoted your answer, thank you! ;) – Armen Michaeli Jun 26 '20 at 15:10
1

The ability to intercept console messages generated by the renderer process, in the main process, was implemented in Electron version v1.8.2-beta.3 (as far as I were able to determine).

To be able to handle these messages, one attaches a "console-message" event handler to the webContents object property of a BrowserWindow object.

A rather straightforward replication of messages by the main process, could be implemented as follows (win refers to a BrowserWindow you want to capture messages for):

const log_level_names = { "-1": "DEBUG", "0": "INFO", "1": "WARN", "2": "ERROR" };
win.webContents.on("console-message", (ev, level, message, line, file) => {
    console.log(`${new Date().toUTCString()}\t${log_level_names[level]}\t${message} (${file}:${line})`);
});
Armen Michaeli
  • 8,625
  • 8
  • 58
  • 95
  • `console.error(new Error('foo'))` from the web page gets sent across as just err.toString() instead of err.stack, right? – Brandon Ros Aug 10 '22 at 04:58