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;
  });
});
Yan Foto
  • 10,850
  • 6
  • 57
  • 88
Don P
  • 60,113
  • 114
  • 300
  • 432
  • Just a small note for whoever stumbles on this: Dev tools are also supported in `` tags as well via the openDevTools() method as documented [here](https://www.electronjs.org/docs/latest/api/webview-tag/#webviewopendevtools) – Martin Gergov Dec 15 '21 at 21:26

17 Answers17

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.

Alex Warren
  • 7,187
  • 2
  • 31
  • 30
  • 5
    Can i `console.log()` to main process from the renderer process? – Fandi Susanto Sep 19 '16 at 04:41
  • 2
    @FandiSusanto, You can use ipcRenderer module to send a message to your main process and, then, console.log() inside it. – arthursfreire Sep 28 '16 at 20:50
  • 29
    What abut in production mode , what will` console.log() ` in main process do – Jimmy Obonyo Abor Nov 16 '16 at 00: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 01 '18 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 '20 at 06:39
  • I call it from neither, and nothing shows up. I have a page that has its own JS script, and I found that not only `console.log` stops working, but also VSCode syntax check stops working. – kakyo Feb 24 '20 at 03:58
  • in a production electron app, running the setup.exe didn't have any cmdprompt output, but my program.exe did have cmdprompt output by using console.log in electron.js, without any special environment variable – Michelle Norris Sep 14 '22 at 19:38
66

You can also add an environment variable in windows:

ELECTRON_ENABLE_LOGGING=1

This will output console messages to your terminal.

deejbee
  • 1,148
  • 11
  • 17
  • 1
    I didn't see any messages in the console until this environment variable was set. – DVK Oct 26 '17 at 15:10
  • 8
    The [docs](https://github.com/electron/electron/blob/master/docs/api/environment-variables.md) 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 '18 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](https://gist.github.com/x-yuri/08f43367eaacb3793b8d33044022571e) to see the effect. – x-yuri Dec 07 '19 at 10:35
  • 2
    Which file is the ELECTRON_ENABLE_LOGGING=1 added to? – half of a glazier Dec 17 '19 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 '19 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.

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.')
raphinesse
  • 19,068
  • 6
  • 39
  • 48
  • 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 '18 at 06:01
  • 1
    Derrick: Try setting the environment variable `ELECTRON_ENABLE_LOGGING=1` (see deejbee's answer) – raphinesse Feb 11 '18 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 '20 at 05: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.');
Pang
  • 9,564
  • 146
  • 81
  • 122
David Figatner
  • 771
  • 8
  • 18
12
process.stdout.write('your output to command prompt console or node js ')
Pang
  • 9,564
  • 146
  • 81
  • 122
cscsandy5
  • 121
  • 1
  • 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. – Toby Speight Apr 05 '17 at 22:00
  • 2
    Now that's what I call the answer, one straight line ! – Tom May 01 '22 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');
Pang
  • 9,564
  • 146
  • 81
  • 122
StefanSL
  • 318
  • 2
  • 11
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

Aiq0
  • 306
  • 1
  • 11
M. Richardson
  • 81
  • 1
  • 3
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

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.

Aiq0
  • 306
  • 1
  • 11
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
crifan
  • 12,947
  • 1
  • 71
  • 56
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.

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
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.

jixaw
  • 47
  • 3
  • 1
    you save my day!!! on win server 2012 it's the only way to make console.log work! – r1si Aug 31 '20 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)

Freddy Daniel
  • 602
  • 11
  • 25
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.

Wale
  • 1,321
  • 16
  • 11
  • 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 '19 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 '19 at 09: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.

pzrq
  • 1,626
  • 1
  • 18
  • 24
0

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

JHM16
  • 649
  • 8
  • 12