Skip to content

Commit

Permalink
fix(initialize): Allow custom sessions, fixes #379, closes #380 (#388)
Browse files Browse the repository at this point in the history
* fix(initialize): fix session-create event missing, fixes #379

* refactor: Cosmetic changes

* feat: Add getSessions and includeFutureSession preload options

---------

Co-authored-by: xuewenG <[email protected]>
  • Loading branch information
megahertz and xuewenG authored Dec 24, 2023
1 parent 00cd210 commit 0ec6d04
Show file tree
Hide file tree
Showing 11 changed files with 146 additions and 31 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Install with [npm](https://npmjs.org/package/electron-log):
import log from 'electron-log/main';

// Optional, initialize the logger for any renderer process
log.initialize({ preload: true });
log.initialize();

log.info('Log from the main process');
```
Expand All @@ -44,10 +44,13 @@ import log from 'electron-log/renderer';
log.info('Log from the renderer process');
```

This function uses sessions to inject a preload script to make the logger
available in a renderer process.

Without a bundler, you can use a global variable `__electronLog`. It contains
only log functions like `info`, `warn` and so on.

There are a few other options how a logger can be initialized for a renderer
There are a few other ways how a logger can be initialized for a renderer
process. [Read more](docs/initialize.md).

### electron-log v2.x, v3.x, v4.x
Expand Down
29 changes: 19 additions & 10 deletions docs/initialize.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,42 @@ and sends it to the main process through IPC.

There are a few ways how a renderer logger could be configured.

## 1. Use some bundler and contextIsolation/sandbox enabled

This way also works without bundler when nodeIntegration is enabled.
## 1. Most common case. Use some bundler and contextIsolation/sandbox enabled

```js
import log from 'electron-log';
import log from 'electron-log/main';

log.initialize();
````

**renderer.ts**
```typescript
import log from 'electron-log';
import log from 'electron-log/renderer';
log.info('Log from the renderer');
````
If for some reason it doesn't work with your bundler, try the following
import in the renderer process:
This method injects a built-in preload script into a renderer process through
sessions. The preload script is injected into the default session and any
sessions created after a `log.initizlie()` call.
### Using custom sessions
If you use another session, make sure it's initialized
after `log.initialize()` call or pass your sessions to the function:
```js
log.initialize({ getSessions: () => [customSession] });
````

`import log from 'electron-log/renderer';`
To disable preload script injection, pass `includeFutureSession: false` option
to the `initizlize` function.

## Use a global instance when no bundler used and nodeIntegration is disabled

**main.js**
```js
import log from 'electron-log';
import log from 'electron-log/main';

log.initialize();
````
Expand All @@ -53,7 +62,7 @@ It's possible to collect logs written by `console.log` in the renderer process

**main.js**
```js
import log from 'electron-log';
import log from 'electron-log/main';

// It makes a renderer logger available trough a global electronLog instance
log.initialize({ spyRendererConsole: true });
Expand Down
1 change: 1 addition & 0 deletions e2e/custom-session/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
18 changes: 18 additions & 0 deletions e2e/custom-session/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>E2E Test</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';">
</head>
<body>

<script>
__electronLog.info('log through global object');
if (window.location.href.includes('test=true')) {
setTimeout(() => window.close(), 50);
}
</script>

</body>
</html>
27 changes: 27 additions & 0 deletions e2e/custom-session/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict';

const { app, BrowserWindow, session } = require('electron');
const path = require('path');
const log = require('../..');

async function createWindow() {
log.initialize({ preload: true });

const PARTITION = 'persist:test';
session.fromPartition(PARTITION);

log.info('log from the main process');

const win = new BrowserWindow({
webPreferences: {
partition: PARTITION,
},
});

const t = process.argv.includes('--test') ? 'true' : 'false';
await win.loadURL(`file://${path.join(__dirname, 'index.html')}?test=${t}`);
}

app
.on('ready', createWindow)
.on('window-all-closed', () => app.quit());
14 changes: 14 additions & 0 deletions e2e/custom-session/main.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

const { expect, test } = require('humile');
const E2eApp = require('../E2eApp');

const app = new E2eApp({ appPath: __dirname });

test(app.appName, async () => {
const logReader = await app.run();
expect(logReader.format()).toEqual([
'log from the main process',
'log through global object',
]);
}, app.timeout);
12 changes: 12 additions & 0 deletions e2e/custom-session/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "electron-log-e2e-custom-session",
"version": "1.0.0",
"private": true,
"main": "main.js",
"scripts": {
"start": "../../node_modules/.bin/electron ."
},
"devDependencies": {
"electron": "*"
}
}
4 changes: 2 additions & 2 deletions src/core/Logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ class Logger {
return check <= pass;
}

initialize({ preload = true, spyRendererConsole = false } = {}) {
this.initializeFn({ logger: this, preload, spyRendererConsole });
initialize(options = {}) {
this.initializeFn({ logger: this, ...options });
}

logData(data, options = {}) {
Expand Down
7 changes: 6 additions & 1 deletion src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,12 @@ declare namespace Logger {

interface MainLogger extends Logger {
initialize(
options?: { preload?: string | boolean, spyRendererConsole?: boolean },
options?: {
getSessions?: () => object[];
includeFutureSessions?: boolean;
preload?: string | boolean;
spyRendererConsole?: boolean;
},
): void;

errorHandler: ErrorHandler<MainErrorHandlerOptions>;
Expand Down
18 changes: 12 additions & 6 deletions src/main/electronApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ module.exports = {
};
},

onAppReady(handler) {
if (electron?.app?.isReady()) {
handler();
} else if (electron?.app?.once) {
electron?.app?.once('ready', handler);
} else {
handler();
}
},

onEveryWebContentsEvent(eventName, handler) {
electron?.webContents?.getAllWebContents().forEach((webContents) => {
webContents.on(eventName, handler);
Expand Down Expand Up @@ -103,9 +113,9 @@ module.exports = {
setPreloadFileForSessions({
filePath,
includeFutureSession = true,
sessions = [electron?.session?.defaultSession],
getSessions = () => [electron?.session?.defaultSession],
}) {
for (const session of sessions.filter(Boolean)) {
for (const session of getSessions().filter(Boolean)) {
setPreload(session);
}

Expand Down Expand Up @@ -142,10 +152,6 @@ module.exports = {

dialog.showErrorBox(title, message);
},

whenAppReady() {
return electron?.app?.whenReady() || Promise.resolve();
},
};

function getApp() {
Expand Down
40 changes: 30 additions & 10 deletions src/main/initialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,38 @@ const electronApi = require('./electronApi');
const preloadInitializeFn = require('../renderer/electron-log-preload');

module.exports = {
initialize({ logger, preload = true, spyRendererConsole = false }) {
electronApi.whenAppReady()
.then(() => {
initialize({
getSessions,
includeFutureSession,
logger,
preload = true,
spyRendererConsole = false,
}) {
electronApi.onAppReady(() => {
try {
if (preload) {
initializePreload(preload);
initializePreload({
getSessions,
includeFutureSession,
preloadOption: preload,
});
}

if (spyRendererConsole) {
initializeSpyRendererConsole(logger);
initializeSpyRendererConsole({ logger });
}
})
.catch(logger.warn);
} catch (err) {
logger.warn(err);
}
});
},
};

function initializePreload(preloadOption) {
function initializePreload({
getSessions,
includeFutureSession,
preloadOption,
}) {
let preloadPath = typeof preloadOption === 'string'
? preloadOption
: path.resolve(__dirname, '../renderer/electron-log-preload.js');
Expand All @@ -42,10 +58,14 @@ function initializePreload(preloadOption) {
fs.writeFileSync(preloadPath, preloadCode, 'utf8');
}

electronApi.setPreloadFileForSessions({ filePath: preloadPath });
electronApi.setPreloadFileForSessions({
filePath: preloadPath,
includeFutureSession,
getSessions,
});
}

function initializeSpyRendererConsole(logger) {
function initializeSpyRendererConsole({ logger }) {
const levels = ['verbose', 'info', 'warning', 'error'];
electronApi.onEveryWebContentsEvent(
'console-message',
Expand Down

0 comments on commit 0ec6d04

Please sign in to comment.