Skip to content

Commit

Permalink
Abstract console.log
Browse files Browse the repository at this point in the history
- in preparation for logging elsewhere
- can be mocked in tests
  • Loading branch information
irahopkinson committed Feb 28, 2023
1 parent 19c32e9 commit 31d42ba
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 25 deletions.
9 changes: 5 additions & 4 deletions src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { autoUpdater } from 'electron-updater';
import log from 'electron-log';
import windowStateKeeper from 'electron-window-state';
import dotnetDataProvider from '@main/services/dotnet-data-provider.service';
import logger from '@shared/util/logger';
import * as NetworkService from '@shared/services/NetworkService';
import papi from '@shared/services/papi';
import { CommandHandler } from '@shared/util/PapiUtil';
Expand Down Expand Up @@ -57,7 +58,7 @@ const installExtensions = async () => {
extensions.map((name) => installer[name]),
forceDownload,
)
.catch(console.log);
.catch(logger.log);
};

/** The path to the app package directory */
Expand Down Expand Up @@ -178,7 +179,7 @@ app
if (mainWindow === null) createWindow();
});
})
.catch(console.log);
.catch(logger.log);

// #endregion

Expand All @@ -188,7 +189,7 @@ const commandHandlers: { [commandName: string]: CommandHandler } = {
echo: async (message: string) => {
/* const start = performance.now(); */
/* const result = */ await papi.commands.sendCommand('addThree', 1, 4, 9);
/* console.log(
/* logger.log(
`addThree(...) = ${result} took ${performance.now() - start} ms`,
); */
return message;
Expand All @@ -215,6 +216,6 @@ const commandHandlers: { [commandName: string]: CommandHandler } = {
// Start the dotnet data provider early so its ready when needed once the
// WebSocket is up.
dotnetDataProvider.start();
})().catch(console.error);
})().catch(logger.error);

// #endregion
5 changes: 3 additions & 2 deletions src/main/services/ServerNetworkConnector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
NetworkConnectorInfo,
} from '@shared/data/InternalConnectionTypes';
import INetworkConnector from '@shared/services/INetworkConnector';
import logger from '@shared/util/logger';
import { Unsubscriber } from '@shared/util/PapiUtil';
import {
ClientConnect,
Expand Down Expand Up @@ -366,7 +367,7 @@ export default class ServerNetworkConnector implements INetworkConnector {
this.nextClientId += 1;

// TODO: probably do something better than just print the error
webSocket.addEventListener('error', console.error);
webSocket.addEventListener('error', logger.error);

webSocket.addEventListener('message', this.onMessage);
webSocket.addEventListener('close', this.onClientDisconnect);
Expand Down Expand Up @@ -400,7 +401,7 @@ export default class ServerNetworkConnector implements INetworkConnector {
/** Closes connection and unregisters a client webSocket when it has disconnected */
private disconnectClient = (webSocket: WebSocket) => {
const clientId = this.getClientIdFromSocket(webSocket);
webSocket.removeEventListener('error', console.error);
webSocket.removeEventListener('error', logger.error);
webSocket.removeEventListener('message', this.onMessage);
webSocket.removeEventListener('close', this.onClientDisconnect);
webSocket.close();
Expand Down
13 changes: 7 additions & 6 deletions src/main/services/dotnet-data-provider.service.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { ChildProcessWithoutNullStreams, spawn } from 'child_process';
import path from 'path';
import logger from '@shared/util/logger';

let dotnet: ChildProcessWithoutNullStreams | undefined;

function killDotnetDataProvider() {
if (!dotnet) return;

if (dotnet.kill()) {
console.log('[dotnet data provider] was killed');
logger.log('[dotnet data provider] was killed');
} else {
console.error(
logger.error(
'[dotnet data provider] was not stopped! Investigate other .kill() options',
);
}
Expand Down Expand Up @@ -47,18 +48,18 @@ function startDotnetDataProvider() {
dotnet = spawn(command, args);

dotnet.stdout.on('data', (data) => {
console.log(`[dotnet data provider] stdout: ${data}`);
logger.log(`[dotnet data provider] stdout: ${data}`);
});

dotnet.stderr.on('data', (data) => {
console.error(`[dotnet data provider] stderr: ${data}`);
logger.error(`[dotnet data provider] stderr: ${data}`);
});

dotnet.on('close', (code, signal) => {
if (signal) {
console.log(`[dotnet data provider] terminated with signal ${signal}`);
logger.log(`[dotnet data provider] terminated with signal ${signal}`);
} else {
console.log(`[dotnet data provider] exited with code ${code}`);
logger.log(`[dotnet data provider] exited with code ${code}`);
}
});
}
Expand Down
19 changes: 10 additions & 9 deletions src/renderer/App.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useCallback, useState } from 'react';
import { MemoryRouter as Router, Routes, Route } from 'react-router-dom';
import * as NetworkService from '@shared/services/NetworkService';
import icon from '@assets/icon.png';
import './App.css';
import logger from '@shared/util/logger';
import * as NetworkService from '@shared/services/NetworkService';
import papi from '@shared/services/papi';
import { getErrorMessage } from '@shared/util/Util';
import usePromise from '@renderer/hooks/usePromise';
Expand All @@ -17,7 +18,7 @@ const testBase: () => Promise<string> = NetworkService.createRequestFunction(
const test = async () => {
/* const start = performance.now(); */
const result = await testBase();
/* console.log(`Test took ${performance.now() - start} ms`); */
/* logger.log(`Test took ${performance.now() - start} ms`); */
return result;
};

Expand All @@ -42,7 +43,7 @@ const executeMany = async <T,>(fn: () => Promise<T>) => {
requestTime[i] = performance.now() - requestTime[i];
return response;
})
.catch((err) => console.error(err));
.catch(logger.error);
}

try {
Expand All @@ -56,15 +57,15 @@ const executeMany = async <T,>(fn: () => Promise<T>) => {
(min, time) => Math.min(min, time),
Number.MAX_VALUE,
);
console.log(
logger.log(
`Of ${numRequests} requests:\n\tAvg response time: ${avgResponseTime} ms\n\tMax response time: ${maxTime} ms\n\tMin response time: ${minTime}\n\tTotal time: ${
finish - start
}\n\tResponse times:`,
requestTime,
);
console.log(responses[responses.length - 1]);
logger.log(responses[responses.length - 1]);
} catch (e) {
console.error(e);
logger.error(e);
}
};

Expand All @@ -82,11 +83,11 @@ const Hello = () => {
async (asyncFn: () => Promise<unknown>) => {
try {
const result = await asyncFn();
console.log(result);
logger.log(result);
setPromiseReturn(JSON.stringify(result));
return result;
} catch (e) {
console.error(e);
logger.error(e);
setPromiseReturn(`Error: ${getErrorMessage(e)}`);
return undefined;
}
Expand All @@ -108,7 +109,7 @@ const Hello = () => {
onClick={async () => {
const start = performance.now();
const result = await runPromise(() => echo('Stuff'));
console.log(
logger.log(
`command:echo '${result}' took ${performance.now() - start} ms`,
);
}}
Expand Down
5 changes: 3 additions & 2 deletions src/shared/services/CommandService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
UnsubPromiseAsync,
} from '@shared/util/PapiUtil';
import { isClient } from '@shared/util/InternalUtil';
import logger from '@shared/util/logger';

/** Whether this service has finished setting up */
let isInitialized = false;
Expand Down Expand Up @@ -109,14 +110,14 @@ export const initialize = memoizeOne(async (): Promise<void> => {
const start = performance.now();
sendCommandUnsafe('echo', 'Hi server!')
.then((response) =>
console.log(
logger.log(
'command:echo Response!!!',
response,
'Response time:',
performance.now() - start,
),
)
.catch((e) => console.error(e));
.catch(logger.error);
}
});

Expand Down
3 changes: 2 additions & 1 deletion src/shared/services/ConnectionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from '@shared/data/InternalConnectionTypes';
import INetworkConnector from '@shared/services/INetworkConnector';
import * as NetworkConnectorFactory from '@shared/services/NetworkConnectorFactory';
import logger from '@shared/util/logger';
import { ComplexResponse } from '@shared/util/PapiUtil';

/** Whether this connector is setting up or has finished setting up its connection and is ready to communicate on the network */
Expand Down Expand Up @@ -188,7 +189,7 @@ export const connect = async (
}

clientId = newConnectorInfo.clientId;
console.log(`Got clientId ${clientId}`);
logger.log(`Got clientId ${clientId}`);

if (!networkConnector) {
if (!connectReject)
Expand Down
2 changes: 1 addition & 1 deletion src/shared/util/Util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {
* @returns message of the error - if object has message, returns message. Otherwise tries to stringify
* @example
* try {...}
* catch (e) { console.log(getErrorMessage(e)) }
* catch (e) { logger.log(getErrorMessage(e)) }
*/
export function getErrorMessage(error: unknown) {
return toErrorWithMessage(error).message;
Expand Down
6 changes: 6 additions & 0 deletions src/shared/util/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Abstract the logger
* For now just use the console logger
*/
const logger = new console.Console(process.stdout, process.stderr);
export default logger;

0 comments on commit 31d42ba

Please sign in to comment.