Network Logging in ElectronJS
Last Updated :
15 Oct, 2020
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
All Native desktop applications can establish internet connections for dynamic functioning. These connections are important to fetch/redirect relevant information for the application such as fetching dynamic content via RESTful APIs, redirecting user requests, etc. It is very important to monitor these active network connections via logging and in case of any failure pinpoint the root cause. Electron provides us with the built-in netLog module for this very purpose. This module is used for Logging active network connections and events for a session.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
netLog Module: The netLog Module is part of the Main Process. To import and use the netLog Module in the Renderer Process, we will be using the remote module provided by Electron. For more details on the remote Module, Refer this link. All methods of the netLog module can only be used after the ready event of the app module gets emitted. Refer to the highlighted code in the main.js file.
- Project Structure:
Example: We will start by building the basic Electron Application by following the given steps.
- Step 1: Navigate to an Empty Directory to setup the project, and run the following command,
npm init
To generate the package.json file. Install Electron using npm if it is not installed.
npm install electron --save-dev
This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the “scripts” key. Install NODE-PING using npm.
npm install ping --save
This package will be used to generate network activity. For more detailed Information, Refer this link. Create the logs.txt file in the assets folder.
package.json:
{
"name": "electron-netlogging",
"version": "1.0.0",
"description": "Network Logging in Electron",
"main": "main.js",
"scripts": {
"start": "electron"
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.2.5"
}
}
- Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We will modify the code to suit our project needs.
main.js:
const { app, BrowserWindow } = require( 'electron' )
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile( 'src/index.html' )
win.webContents.openDevTools()
}
app.whenReady().then(createWindow)
app.on( 'window-all-closed' , () => {
if (process.platform !== 'darwin' ) {
app.quit()
}
})
app.on( 'activate' , () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
|
- Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We will modify the code to suit our project needs.
index.html:
<!DOCTYPE html>
< html >
< head >
< meta charset = "UTF-8" >
< title >Hello World!</ title >
< meta http-equiv = "Content-Security-Policy"
content = "script-src 'self' 'unsafe-inline';" />
</ head >
< body >
< h1 >Hello World!</ h1 > We are using node
< script >
document.write(process.versions.node)
</ script >, Chrome
< script >
document.write(process.versions.chrome)
</ script >, and Electron
< script >
document.write(process.versions.electron)
</ script >.
< script src = "index.js" ></ script >
</ body >
</ html >
|
- Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:
npm start
The netLog module supports following Instance methods and Instance Properties. It does not support any Instance events. All of the Instance methods and Instance Properties have been demonstrated in the code.
Note – The log file generated is in JSON Format. For this tutorial, for every network activity, the log file will be overwritten.
- netLog.startLogging(path, options): To resolve the given path and start recording the active network events and connections to the log file at the given path. It returns a Promise and it gets resolved when the netLog has begun recording to the log file. For more detailed Information, Refer this link.
- path: String Points to the custom log file to record the Network event logs.
- options: Object (Optional) The options Object consists of the following parameters,
- captureMode: String (Optional) It represents on the Kind of the data that needs to be captured from the Network events. By default, it only captures the metadata of the network requests. This setting is represented by default value. Setting the value as includeSensitive will include cookies and authentication data, if any, for the captured network requests. Setting this value as everything will include all bytes transferred on sockets as well. In this tutorial, logging is demonstrated with value set as everything in the code.
- netLog.stopLogging(): Stops all Network event recording activity. If this method is not called, the recording automatically stops when app quits. It does not take in any parameters. It returns a
Promise
with String datatype. It resolves to the file path of the logs file.
- netLog.currentlyLogging: This Instance property returns a Boolean value indicating whether the network event logs are being recorded or not. It is a Readonly Property.
index.html: Add the following snippet in that file.
< br >< br >
< button id = "external" >
Open GeeksForGeeks.org
</ button >
< br >< br >
< button id = "check" >
Ping Google.com
</ button >
|
index.js: Add the following snippet in that file.
const electron = require( 'electron' );
const path = require( 'path' );
const ping = require( 'ping' );
const netLog = electron.remote.netLog;
const shell = electron.shell;
var external = document.getElementById( 'external' );
var loggingPath = path.join(__dirname, '../assets/logs.txt' );
var options = {
captureMode: 'everything' ,
}
external.addEventListener( 'click' , (event) => {
netLog.startLogging(loggingPath, options).then(() => {
console.log( 'Starting Network Recording' )
});
console.log( 'Currently Logging - ' , netLog.currentlyLogging);
netLog.stopLogging().then((path) => {
console.log( 'Network Logs written to Path - ' , path);
});
});
var check = document.getElementById( 'check' );
check.addEventListener( 'click' , (event) => {
netLog.startLogging(loggingPath, options);
ping.promise.probe( 'www.google.com' )
.then( function (res) {
console.log(res);
console.log( 'Currently Logging - ' , netLog.currentlyLogging);
netLog.stopLogging().then((path) => {
console.log( 'Network Logs written to Path - ' , path);
});
});
});
|
Output:
Note: The logs.txt file consists of a vast range of information for the Network.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...