Using console.log() in Electron app

Electron

Electron Problem Overview


How can I log data or messages to the console in my Electron app?

This really basic hello world opens the dev tools by default, by I am unable to use console.log('hi'). Is there an alternative for Electron?

main.js

var app = require('app');
var BrowserWindow = require('browser-window');

require('crash-reporter').start();

var mainWindow = null;

app.on('window-all-closed', function() {
  // Mac OS X - close is done explicitly with Cmd + Q, not just closing windows
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', function(){
  mainWindow = new BrowserWindow({ width: 800, height: 600});

  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  mainWindow.openDevTools();

  mainWindow.on('closed', function(){
    mainWindow = null;
  });
});

Electron Solutions


Solution 1 - Electron

console.log works, but where it logs to depends on whether you call it from the main process or the renderer process.

If you call it from the renderer process (i.e. JavaScript that is included from your index.html file) it will be logged to the dev tools window.

If you call it from the main process (i.e. in main.js) it will work the same way as it does in Node - it will log to the terminal window. If you're starting your Electron process from the Terminal using electron . you can see your console.log calls from the main process there.

Solution 2 - Electron

You can also add an environment variable in windows:

ELECTRON_ENABLE_LOGGING=1

This will output console messages to your terminal.

Solution 3 - Electron

There is another way of logging to the console from inside the renderer process. Given this is Electron, you can access Node's native modules. This includes the console module.

var nodeConsole = require('console');
var myConsole = new nodeConsole.Console(process.stdout, process.stderr);
myConsole.log('Hello World!');

When this code is run from inside the renderer process, you will get Hello World! in the terminal you ran Electron from.

See https://nodejs.org/api/console.html for further documentation on the console module.

Solution 4 - Electron

Yet another possibility is accessing the main process console using remote.getGlobal(name):

const con = require('electron').remote.getGlobal('console')
con.log('This will be output to the main process console.')

Solution 5 - Electron

Adding to M. Damian's answer, here's how I set it up so I could access the main process's console from any renderer.

In your main app, add:

const electron = require('electron');
const app = electron.app;
const console = require('console');
...
app.console = new console.Console(process.stdout, process.stderr);

In any renderer, you can add:

const remote = require('electron').remote;
const app = remote.app;
...
app.console.log('This will output to the main process console.');

Solution 6 - Electron

process.stdout.write('your output to command prompt console or node js ')

Solution 7 - Electron

You can use the npm package electron-log https://www.npmjs.com/package/electron-log

It will log your error, warn, info, verbose, debug, silly outputs in your native os log.

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

log.info('Hello, log');
log.error('Damn it, an error');

Solution 8 - Electron

Sorry to raise an old thread but this is the top result for "how to output console.log to terminal" (or similar searches.

For anyone looking to gain a bit more control over what is output to the terminal you can use webContents.on('console-message') like so:

mainWindow.webContents.on('console-message', (event, level, message, line, sourceId) => {
      console.log(message + " " +sourceId+" ("+line+")");
});

See:

webContents Documentation

webContents entry on BrowserWindow docs

Solution 9 - Electron

This is a follow up to cscsandy5's answer for some addition information, info from here

process.stdout.write('your output to command prompt console or node js ')

This code works great for just outputting a simple debug message to the terminal window you launched the electron app from and is is what console.log is build on top of.

Here is an example snippet (based on tutorialspoint electon tutorial) of a jQuery script that will write hello to the terminal every time the button is pressed (warning: you need to add your own line breaks in the output strings!)

let $ = require('jquery')
var clicks = 0;

$(function() {
    $('#countbtn').click(function() {
        //output hello <<<<<<<<<<<<<<<<<<<<<<<
        process.stdout.write('hello')
      
        $('#click-counter').text(++clicks);
    });

    $('#click-counter').text(clicks);
});

Solution 10 - Electron

After some investigation, here my understanding:

Code

(1) main.js


const createPyProc = () => {
  console.log('In createPyProc')
...
  console.log('scriptStart=%s', scriptStart)
...
  console.log('scriptOther=%s', scriptOther)
...
}

...

let mainWindow = null

const createWindow = () => {
  mainWindow = new BrowserWindow(
    {
      width: 1024,
      height: 768,
      webPreferences: {
        nodeIntegration: true,
      }
    }
  )
  mainWindow.loadURL(require('url').format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
  mainWindow.webContents.openDevTools()

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}
...

Note: which use openDevTools to opened Electron Dev Tools

(2) render.js

const zerorpc = require("zerorpc")
...
    console.log("clientStart %d server is ready", PORT_START)
...
})

(3) render.js is called by: index.html

<!DOCTYPE html>
<html>
...
  <script>
    require('./renderer.js')
  </script>
</html>

console.log

Output Logic

  • two process and its console.log output:
    • main process = NodeJS process = here Electron UI process
      • -> console.log in main.js will output log to here
    • render process
      • -> console.log in render.js will output log to here

Screenshot Example

  • DEBUG=Development mode
    • run ./node_modules/.bin/electron .
  • Production=Release mode = the xxx.app pacakged by eletron-builder
    • run /path_to_your_packaged_mac_app/xxx.app/Contents/MacOS/yourBinaryExecutable
    • added export ELECTRON_ENABLE_LOGGING=true, render.js console.log ALSO output to main process terminal

Solution 11 - Electron

This is what I use:

let mainWindow // main window reference, you should assign it below 'mainWindow = new BrowserWindow'

function log(...data) {
  mainWindow.webContents.executeJavaScript("console.log('%cFROM MAIN', 'color: #800', '" + data + "');");
}

Example use (same as console.log):

log('Error', { msg: 'a common log message' })
log('hello')

Source: https://github.com/fuse-box/fuse-box-electron-seed/tree/master/src/main in the logger.js file, here you can see a real use case.

Solution 12 - Electron

console.log() will work fine for debugging. As the electron is built on top of browser, it has DevTools support you can use devtools for debugging purpose. However, there is a hysterical behaviour of console.log() method. When you call the console.log() from main process of electron app, it will output to the terminal window from where you just launched the app and when you call it from renderer process it will output to the DevTools console.

Solution 13 - Electron

Everything Alex Warren wrote is true. Important here is how Electron is started. If you use the standard script in the package.json file it will not work. To make console.log() work replace the old script with this new one.

Old one:

"scripts": {
    "start": "electron ."
}

New one:

"scripts": {
    "start": ".\\node_modules\\electron\\dist\\electron.exe ."
}

Now all console.log() calls are displayed in the terminal as well.

Solution 14 - Electron

Well, this is 2019 and I cant believe no one mentioned this trick in all the answers above. Ok, so, how about logging directly to the browser console directly from the main? I provided my answer here: https://stackoverflow.com/a/58913251/8764808 Take a look.

Solution 15 - Electron

With this You can use developer tools of main Browser window to see logs

	function logEverywhere(s) {
		if (_debug === true) {
			console.log(s);
            // mainWindow is main browser window of your app
			if (mainWindow && mainWindow.webContents) {
				mainWindow.webContents.executeJavaScript(`console.log("${s}")`);
			}
		}
	}

Example logEverywhere('test') will output // test in console panel of main browser window's developer tools

You may need enhance this method to accept multiple args (You can done it with spread operator by es6)

Solution 16 - Electron

A project I'm working on was using electron-react-boilerplate. That has [email protected], which somehow via cross-unzip causes a process to crash with Error: Exited with code 9 .

Upgrading to [email protected], as proposed in [email protected] resolved it so my console.log, console.error, etc statements worked as expected.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDon PView Question on Stackoverflow
Solution 1 - ElectronAlex WarrenView Answer on Stackoverflow
Solution 2 - ElectrondeejbeeView Answer on Stackoverflow
Solution 3 - ElectronM. Damian MulliganView Answer on Stackoverflow
Solution 4 - ElectronraphinesseView Answer on Stackoverflow
Solution 5 - ElectronDavid FigatnerView Answer on Stackoverflow
Solution 6 - Electroncscsandy5View Answer on Stackoverflow
Solution 7 - ElectronStefanSLView Answer on Stackoverflow
Solution 8 - ElectronM. RichardsonView Answer on Stackoverflow
Solution 9 - ElectronHarrison TelferView Answer on Stackoverflow
Solution 10 - ElectroncrifanView Answer on Stackoverflow
Solution 11 - ElectronCarlos GalarzaView Answer on Stackoverflow
Solution 12 - ElectronKiran ManiyaView Answer on Stackoverflow
Solution 13 - ElectronjixawView Answer on Stackoverflow
Solution 14 - ElectronWaleView Answer on Stackoverflow
Solution 15 - ElectronFreddy DanielView Answer on Stackoverflow
Solution 16 - ElectronpzrqView Answer on Stackoverflow