Programming

Electron 앱에서 console.log () 사용

procodes 2020. 8. 18. 19:24
반응형

Electron 앱에서 console.log () 사용


Electron 앱의 콘솔에 데이터 나 메시지를 어떻게 기록 할 수 있습니까?

이 정말 기본적인 hello world는 기본적으로 개발 도구를 엽니 다 console.log('hi'). 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;
  });
});

console.log 작동하지만 로그 위치는 기본 프로세스에서 호출하는지 렌더러 프로세스에서 호출하는지에 따라 다릅니다.

렌더러 프로세스 (예 : index.html파일에 포함 된 JavaScript)에서 호출 하면 개발 도구 창에 기록됩니다.

메인 프로세스 (예 :)에서 호출하면 main.jsNode에서와 같은 방식으로 작동합니다. 터미널 창에 기록됩니다. 터미널에서 Electron 프로세스를 시작 하는 경우 메인 프로세스 electron .console.log호출을 볼 수 있습니다.


Windows에서 환경 변수를 추가 할 수도 있습니다.

ELECTRON_ENABLE_LOGGING=1

그러면 터미널에 콘솔 메시지가 출력됩니다.


렌더러 프로세스 내부에서 콘솔에 로깅하는 또 다른 방법이 있습니다. 이것이 Electron이므로 Node의 기본 모듈에 액세스 할 수 있습니다. 여기에는 console모듈 이 포함됩니다 .

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

이 코드가 렌더러 프로세스 내부에서 실행되면 Hello World!Electron을 실행 한 터미널로 이동하게됩니다.

모듈 에 대한 추가 문서는 https://nodejs.org/api/console.html참조 하십시오console .


또 다른 가능성은 remote.getGlobal(name)다음을 사용하여 기본 프로세스 콘솔에 액세스하는 것입니다 .

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

M. Damian의 답변에 추가하여, 모든 렌더러에서 기본 프로세스의 콘솔에 액세스 할 수 있도록 설정하는 방법은 다음과 같습니다.

기본 앱에서 다음을 추가하십시오.

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

모든 렌더러에서 다음을 추가 할 수 있습니다.

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

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

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

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

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.


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.


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


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.


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)

참고URL : https://stackoverflow.com/questions/31759367/using-console-log-in-electron-app

반응형