162

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;
  });
});
1
  • Just a small note for whoever stumbles on this: Dev tools are also supported in <webview> tags as well via the openDevTools() method as documented here Dec 15, 2021 at 21:26

17 Answers 17

206

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.

7
  • 5
    Can i console.log() to main process from the renderer process? Sep 19, 2016 at 4:41
  • 2
    @FandiSusanto, You can use ipcRenderer module to send a message to your main process and, then, console.log() inside it. Sep 28, 2016 at 20:50
  • 29
    What abut in production mode , what will` console.log() ` in main process do Nov 16, 2016 at 0:10
  • 30
    @JimmyObonyoAbor To attach a console to a production electron app and get the console output in your terminal run the following in a terminal./path/to/release/MyProgram.app/Contents/MacOS/MyProgram. This will run the binary MyProgram and allow you to view the process console.log events in a terminal.
    – datUser
    Feb 1, 2018 at 16:34
  • how can i still log stuff to terminal after resetting the app via app.relaunch() and app.exit(0)???
    – oldboy
    Jan 24, 2020 at 6:39
66

You can also add an environment variable in windows:

ELECTRON_ENABLE_LOGGING=1

This will output console messages to your terminal.

5
  • 1
    I didn't see any messages in the console until this environment variable was set.
    – DVK
    Oct 26, 2017 at 15:10
  • 8
    The docs say that should be set to true and that setting it to true "prints Chrome's internal logging to the console", which is not what OP wants.
    – pushkin
    Jan 24, 2018 at 21:01
  • @pushkin It works with ELECTRON_ENABLE_LOGGING=1 as well. And as for what the OP wants, what is it then? Take a look at the following gist to see the effect.
    – x-yuri
    Dec 7, 2019 at 10:35
  • 2
    Which file is the ELECTRON_ENABLE_LOGGING=1 added to? Dec 17, 2019 at 14:30
  • 3
    @Still_learning you set it as an environment variable. so from Windows command line set ELECTRON_ENABLE_LOGGING=true
    – pushkin
    Dec 17, 2019 at 21:28
39

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.

1
  • It works for me only if I don't use console.log in main.js at all
    – Chan Tzish
    Jul 19, 2021 at 5:46
21

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.')
3
  • 2
    This works great, but how can we catch the entire console output; ie- without having to call a special function; such that exceptions and errors are also output ?
    – Derrick
    Feb 10, 2018 at 6:01
  • 1
    Derrick: Try setting the environment variable ELECTRON_ENABLE_LOGGING=1 (see deejbee's answer)
    – raphinesse
    Feb 11, 2018 at 10:08
  • I'm trying to use inside a background script for an extension, and it's not working, unclear as to why. (background scripts get loaded in as background windows, basically)
    – Narfanator
    Jan 14, 2020 at 5:22
15

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.');
0
12
process.stdout.write('your output to command prompt console or node js ')
2
  • 6
    Although this code may help to solve the problem, it doesn't explain why and/or how it answers the question. Providing this additional context would significantly improve its long-term value. Please edit your answer to add explanation, including what limitations and assumptions apply. Apr 5, 2017 at 22:00
  • 2
    Now that's what I call the answer, one straight line !
    – Tom
    May 1, 2022 at 15:24
10

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');
8

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'):

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

See:

webContents Documentation
webContents entry on BrowserWindow docs

6

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);
});
6

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
6

This is what I use:

let mainWindow = new BrowserWindow(/*...*/) // Your browser window

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.

1
  • Data needs to be encoded though (as JSON string?) to avoid JS code injections.
    – Zmey
    Nov 28, 2019 at 22:14
4

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.

3

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.

1
  • 1
    you save my day!!! on win server 2012 it's the only way to make console.log work!
    – r1si
    Aug 31, 2020 at 17:29
3

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)

3

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.

2
  • Thanks @Wale! Would you mind inlining your answer? I don't mind the link to another question, but a lot of mods on here get pissy about cross linking answers even with SO.
    – Don P
    Nov 19, 2019 at 21:15
  • I would have actually loved to, but again, the last time I tried doing that, I was reprimanded for duplicating answers.
    – Wale
    Nov 20, 2019 at 9:59
1

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

Upgrading to electron-devtools-installer@3.1.1, as proposed in electron-react-boilerplate@v2.0.0 resolved it so my console.log, console.error, etc statements worked as expected.

0

for log purpose, i would recommend you to use the electron-log package

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.