Centralize log file and refactor desktop logging

- Migrate to `electron-log` v5.X.X, centralizing log files to adhere to
  best-practices.
- Add critical event logging in the log file.
- Replace `ElectronLog` type with `LogFunctions` for better abstraction.
- Unify log handling in `desktop-runtime-error` by removing
  `renderer.log` due to `electron-log` v5 changes.
- Update and extend logger interfaces, removing 'I' prefix and adding
  common log levels to abstract `electron-log` completely.
- Move logger interfaces to the application layer as it's cross-cutting
  concern, meanwhile keeping the implementations in the infrastructure
  layer.
- Introduce `useLogger` hook for easier logging in Vue components.
- Simplify `WindowVariables` by removing nullable properties.
- Improve documentation to clearly differentiate between desktop and web
  versions, outlining specific features of each.
This commit is contained in:
undergroundwires
2023-12-02 11:50:25 +01:00
parent 8f5d7ed3cf
commit 08dbfead7c
40 changed files with 347 additions and 191 deletions

View File

@@ -1,7 +1,7 @@
import { app, dialog } from 'electron';
import { autoUpdater, UpdateInfo } from 'electron-updater';
import { ProgressInfo } from 'electron-builder';
import log from 'electron-log';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import { UpdateProgressBar } from './UpdateProgressBar';
export async function handleAutoUpdate() {
@@ -23,11 +23,11 @@ function startHandlingUpdateProgress() {
On macOS, download-progress event is not called.
So the indeterminate progress will continue until download is finished.
*/
log.debug('@download-progress@\n', progress);
ElectronLogger.debug('@download-progress@\n', progress);
progressBar.showProgress(progress);
});
autoUpdater.on('update-downloaded', async (info: UpdateInfo) => {
log.info('@update-downloaded@\n', info);
ElectronLogger.info('@update-downloaded@\n', info);
progressBar.close();
await handleUpdateDownloaded();
});

View File

@@ -2,12 +2,12 @@ import fs from 'fs';
import path from 'path';
import { app, dialog, shell } from 'electron';
import { UpdateInfo } from 'electron-updater';
import log from 'electron-log';
import fetch from 'cross-fetch';
import { ProjectInformation } from '@/domain/ProjectInformation';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { Version } from '@/domain/Version';
import { parseProjectInformation } from '@/application/Parser/ProjectInformationParser';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import { UpdateProgressBar } from './UpdateProgressBar';
export function requiresManualUpdate(): boolean {
@@ -64,16 +64,16 @@ async function askForVisitingWebsiteForManualUpdate(): Promise<ManualDownloadDia
}
async function download(info: UpdateInfo, project: ProjectInformation) {
log.info('Downloading update manually');
ElectronLogger.info('Downloading update manually');
const progressBar = new UpdateProgressBar();
progressBar.showIndeterminateState();
try {
const filePath = `${path.dirname(app.getPath('temp'))}/privacy.sexy/${info.version}-installer.dmg`;
const parentFolder = path.dirname(filePath);
if (fs.existsSync(filePath)) {
log.info('Update is already downloaded');
ElectronLogger.info('Update is already downloaded');
await fs.promises.unlink(filePath);
log.info(`Deleted ${filePath}`);
ElectronLogger.info(`Deleted ${filePath}`);
} else {
await fs.promises.mkdir(parentFolder, { recursive: true });
}
@@ -99,20 +99,20 @@ async function downloadFileWithProgress(
progressHandler: ProgressCallback,
) {
// We don't download through autoUpdater as it cannot download DMG but requires distributing ZIP
log.info(`Fetching ${url}`);
ElectronLogger.info(`Fetching ${url}`);
const response = await fetch(url);
if (!response.ok) {
throw Error(`Unable to download, server returned ${response.status} ${response.statusText}`);
}
const contentLengthString = response.headers.get('content-length');
if (contentLengthString === null || contentLengthString === undefined) {
log.error('Content-Length header is missing');
ElectronLogger.error('Content-Length header is missing');
}
const contentLength = +(contentLengthString ?? 0);
const writer = fs.createWriteStream(filePath);
log.info(`Writing to ${filePath}, content length: ${contentLength}`);
ElectronLogger.info(`Writing to ${filePath}, content length: ${contentLength}`);
if (Number.isNaN(contentLength) || contentLength <= 0) {
log.error('Unknown content-length', Array.from(response.headers.entries()));
ElectronLogger.error('Unknown content-length', Array.from(response.headers.entries()));
progressHandler = () => { /* do nothing */ };
}
const reader = getReader(response);
@@ -137,9 +137,9 @@ async function streamWithProgress(
receivedLength += chunk.length;
const percentage = Math.floor((receivedLength / totalLength) * 100);
progressHandler(percentage);
log.debug(`Received ${receivedLength} of ${totalLength}`);
ElectronLogger.debug(`Received ${receivedLength} of ${totalLength}`);
}
log.info('Downloaded successfully');
ElectronLogger.info('Downloaded successfully');
}
function getReader(response: Response): NodeJS.ReadableStream | undefined {

View File

@@ -1,7 +1,7 @@
import ProgressBar from 'electron-progressbar';
import { ProgressInfo } from 'electron-builder';
import { app, BrowserWindow } from 'electron';
import log from 'electron-log';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
export class UpdateProgressBar {
private progressBar: ProgressBar | undefined;
@@ -81,7 +81,7 @@ const progressBarFactory = {
progressBar.detail = 'Download completed.';
})
.on('aborted', (value: number) => {
log.info(`progress aborted... ${value}`);
ElectronLogger.info(`Progress aborted... ${value}`);
})
.on('progress', (value: number) => {
progressBar.detail = `${value}% ...`;

View File

@@ -1,5 +1,5 @@
import { autoUpdater, UpdateInfo } from 'electron-updater';
import log from 'electron-log';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import { handleManualUpdate, requiresManualUpdate } from './ManualUpdater';
import { handleAutoUpdate } from './AutoUpdater';
@@ -8,21 +8,21 @@ interface IUpdater {
}
export function setupAutoUpdater(): IUpdater {
autoUpdater.logger = log;
autoUpdater.logger = ElectronLogger;
// Disable autodownloads because "checking" and "downloading" are handled separately based on the
// current platform and user's choice.
autoUpdater.autoDownload = false;
autoUpdater.on('error', (error: Error) => {
log.error('@error@\n', error);
ElectronLogger.error('@error@\n', error);
});
let isAlreadyHandled = false;
autoUpdater.on('update-available', async (info: UpdateInfo) => {
log.info('@update-available@\n', info);
ElectronLogger.info('@update-available@\n', info);
if (isAlreadyHandled) {
log.info('Available updates is already handled');
ElectronLogger.info('Available updates is already handled');
return;
}
isAlreadyHandled = true;

View File

@@ -3,9 +3,10 @@
import {
app, protocol, BrowserWindow, shell, screen,
} from 'electron';
import log from 'electron-log/main';
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer';
import log from 'electron-log';
import { validateRuntimeSanity } from '@/infrastructure/RuntimeSanity/SanityChecks';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import { setupAutoUpdater } from './Update/Updater';
import {
APP_ICON_PATH, PRELOADER_SCRIPT_PATH, RENDERER_HTML_PATH, RENDERER_URL,
@@ -23,6 +24,7 @@ protocol.registerSchemesAsPrivileged([
]);
setupLogger();
validateRuntimeSanity({
// Metadata is used by manual updates.
validateEnvironmentVariables: true,
@@ -89,7 +91,7 @@ app.on('ready', async () => {
try {
await installExtension(VUEJS_DEVTOOLS);
} catch (e) {
log.error('Vue Devtools failed to install:', e.toString());
ElectronLogger.error('Vue Devtools failed to install:', e.toString());
}
}
createWindow();
@@ -123,7 +125,7 @@ function loadApplication(window: BrowserWindow) {
updater.checkForUpdates();
}
// Do not remove [WINDOW_INIT]; it's a marker used in tests.
log.info('[WINDOW_INIT] Main window initialized and content loading.');
ElectronLogger.info('[WINDOW_INIT] Main window initialized and content loading.');
}
function configureExternalsUrlsOpenBrowser(window: BrowserWindow) {
@@ -150,5 +152,7 @@ function getWindowSize(idealWidth: number, idealHeight: number) {
}
function setupLogger(): void {
// log.initialize(); ← We inject logger to renderer through preloader, this is not needed.
log.transports.file.level = 'silly';
log.eventLogger.startLogging();
}

View File

@@ -1,13 +1,12 @@
import log from 'electron-log';
import { createNodeSystemOperations } from '@/infrastructure/SystemOperations/NodeSystemOperations';
import { createElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import { ILogger } from '@/infrastructure/Log/ILogger';
import { Logger } from '@/application/Common/Log/Logger';
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
import { convertPlatformToOs } from './NodeOsMapper';
export function provideWindowVariables(
createSystem = createNodeSystemOperations,
createLogger: () => ILogger = () => createElectronLogger(log),
createLogger: () => Logger = () => createElectronLogger(),
convertToOs = convertPlatformToOs,
): WindowVariables {
return {

View File

@@ -1,8 +1,8 @@
// This file is used to securely expose Electron APIs to the application.
import { contextBridge } from 'electron';
import log from 'electron-log';
import { validateRuntimeSanity } from '@/infrastructure/RuntimeSanity/SanityChecks';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import { provideWindowVariables } from './WindowVariablesProvider';
validateRuntimeSanity({
@@ -20,4 +20,4 @@ Object.entries(windowVariables).forEach(([key, value]) => {
});
// Do not remove [PRELOAD_INIT]; it's a marker used in tests.
log.info('[PRELOAD_INIT] Preload script successfully initialized and executed.');
ElectronLogger.info('[PRELOAD_INIT] Preload script successfully initialized and executed.');