Skip to content

Commit

Permalink
added custom electron-log logger, husky post-commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pavlobu committed Aug 31, 2020
1 parent c8a66d1 commit 9856f41
Show file tree
Hide file tree
Showing 14 changed files with 326 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { BrowserRouter as Router } from 'react-router-dom';
import renderer from 'react-test-renderer';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import Counter from '../../../app/features/counter/Counter';
import * as counterSlice from '../../../app/features/counter/counterSlice';
import Counter from './Counter';
import * as counterSlice from './counterSlice';

Enzyme.configure({ adapter: new Adapter() });
jest.useFakeTimers();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { AnyAction } from 'redux';
import counterReducer, {
increment,
decrement,
} from '../../app/features/counter/counterSlice';
import counterReducer, { increment, decrement } from './counterSlice';

describe('reducers', () => {
describe('counter', () => {
Expand Down
9 changes: 6 additions & 3 deletions app/server/inactive_rooms.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
/* eslint-disable no-console */
import getStore from './store';
import Logger from '../utils/logger';

const log = new Logger('app/server/inactive_rooms.ts');

export default async function pollForInactiveRooms() {
const store = getStore();

console.log('Checking for inactive rooms...');
log.info('Checking for inactive rooms...');
const rooms = (await store.getAll('rooms')) || {};
console.log(`${Object.keys(rooms).length} rooms found`);
log.info(`${Object.keys(rooms).length} rooms found`);

Object.keys(rooms).forEach(async (roomId) => {
const room = JSON.parse(rooms[roomId]);
Expand All @@ -15,7 +18,7 @@ export default async function pollForInactiveRooms() {
timeSinceUpdatedInSeconds / 60 / 60 / 24
);
if (timeSinceUpdatedInDays > 7) {
console.log(
log.info(
`Deleting roomId ${roomId} which hasn't been used in ${timeSinceUpdatedInDays} days`
);
await store.del('rooms', roomId);
Expand Down
12 changes: 10 additions & 2 deletions app/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ import Socket from './socket';
import pollForInactiveRooms from './inactive_rooms';
import getStore from './store';

import Logger from '../utils/logger';

const log = new Logger('app/server/index.ts');

// const log = (...args) => {
// logger.
// };

let isDev;
try {
// eslint-disable-next-line global-require
Expand Down Expand Up @@ -101,7 +109,7 @@ const init = async (PORT: number) => {
pollForInactiveRooms();

return server.listen(PORT, () => {
console.log(`Signaling server is online at port ${PORT}`);
log.info(`Signaling server is online at port ${PORT}`);
});
};

Expand All @@ -123,7 +131,7 @@ class SignalingServer {
public async start(): Promise<Server> {
this.port = await getPort({ port: 3131 });
this.server = await init(this.port);
console.log(`\n\nDeskreen signaling server started at port: ${this.port}`);
log.info(`Deskreen signaling server started at port: ${this.port}`);
return this.server;
}

Expand Down
1 change: 1 addition & 0 deletions app/server/socket.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable no-async-promise-executor */
import regeneratorRuntime from 'regenerator-runtime';
import _ from 'lodash';
import Io from 'socket.io';
// eslint-disable-next-line import/no-cycle
Expand Down
92 changes: 92 additions & 0 deletions app/utils/logger.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import Logger from './logger';

describe('LoggerWithFilePrefix that uses electron-log', () => {
const filePath = 'some/file/path';
let log = new Logger(filePath);
const mockLoggerInfoProperty = jest.fn();
const mockLoggerErrorProperty = jest.fn();
const mockLoggerWarnProperty = jest.fn();
const mockLoggerVerboseProperty = jest.fn();
const mockLoggerDebugProperty = jest.fn();
const mockLoggerSillyProperty = jest.fn();

beforeEach(() => {
mockLoggerInfoProperty.mockClear();
mockLoggerErrorProperty.mockClear();
mockLoggerWarnProperty.mockClear();
mockLoggerVerboseProperty.mockClear();
mockLoggerDebugProperty.mockClear();
mockLoggerDebugProperty.mockClear();

log = new Logger(filePath);
Object.defineProperty(log, 'electronLog', {
value: {
info: mockLoggerInfoProperty,
error: mockLoggerErrorProperty,
warn: mockLoggerWarnProperty,
verbose: mockLoggerVerboseProperty,
debug: mockLoggerDebugProperty,
silly: mockLoggerSillyProperty,
},
});
});
it('should use internal electronLog.info() with filePath as first argument, when .info() is called', () => {
log.info('some info() log here');

expect(mockLoggerInfoProperty).toHaveBeenCalledWith(
filePath,
expect.anything(),
expect.anything()
);
});

it('should use internal electronLog.error() with filePath as first argument, when .error() is called', () => {
log.error('some error() log here');

expect(mockLoggerErrorProperty).toHaveBeenCalledWith(
filePath,
expect.anything(),
expect.anything()
);
});

it('should use internal electronLog.warn() with filePath as first argument, when .warn() is called', () => {
log.warn('some warn() log here');

expect(mockLoggerWarnProperty).toHaveBeenCalledWith(
filePath,
expect.anything(),
expect.anything()
);
});

it('should use internal electronLog.verbose() with filePath as first argument, when .verbose() is called', () => {
log.verbose('some verbose() log here');

expect(mockLoggerVerboseProperty).toHaveBeenCalledWith(
filePath,
expect.anything(),
expect.anything()
);
});

it('should use internal electronLog.debug() with filePath as first argument, when .debug() is called', () => {
log.debug('some debug() log here');

expect(mockLoggerDebugProperty).toHaveBeenCalledWith(
filePath,
expect.anything(),
expect.anything()
);
});

it('should use internal electronLog.silly() with filePath as first argument, when .silly() is called', () => {
log.silly('some silly() log here');

expect(mockLoggerSillyProperty).toHaveBeenCalledWith(
filePath,
expect.anything(),
expect.anything()
);
});
});
45 changes: 45 additions & 0 deletions app/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
const log = require('electron-log');

log.transports.file.level = 'warn';

if (process.env.NODE_ENV !== 'production') {
log.transports.console.level = 'silly';
} else {
log.transports.console.level = 'silly'; // TODO: make false when doing release
}

export default class LoggerWithFilePrefix {
filenamePath: string;

electronLog: typeof log;

constructor(_filenamePath: string) {
this.filenamePath = _filenamePath;
this.electronLog = log;
}

error(...args: any[]) {
this.electronLog.error(this.filenamePath, ':', ...args);
}

warn(...args: any[]) {
this.electronLog.warn(this.filenamePath, ':', ...args);
}

info(...args: any[]) {
this.electronLog.info(this.filenamePath, ':', ...args);
}

verbose(...args: any[]) {
this.electronLog.verbose(this.filenamePath, ':', ...args);
}

debug(...args: any[]) {
this.electronLog.debug(this.filenamePath, ':', ...args);
}

silly(...args: any[]) {
this.electronLog.silly(this.filenamePath, ':', ...args);
}
}
9 changes: 9 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ module.exports = (api) => {
[require('@babel/plugin-proposal-class-properties'), { loose: true }],
require('@babel/plugin-proposal-json-strings'),

// Stage 4
[
require('@babel/plugin-transform-runtime'),
{
helpers: false,
regenerator: true,
},
],

...(development ? developmentPlugins : productionPlugins),
],
};
Expand Down
17 changes: 13 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,14 @@
"homepage": "https://github.com/pavlobu/deskreen#readme",
"jest": {
"testURL": "http://localhost/",
"coveragePathIgnorePatterns": ["/node_modules/", "app/client"],
"testPathIgnorePatterns": ["/node_modules/", "app/client"],
"coveragePathIgnorePatterns": [
"/node_modules/",
"app/client"
],
"testPathIgnorePatterns": [
"/node_modules/",
"app/client"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/internals/mocks/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy"
Expand Down Expand Up @@ -198,6 +204,7 @@
"@babel/plugin-syntax-import-meta": "^7.10.4",
"@babel/plugin-transform-react-constant-elements": "^7.10.4",
"@babel/plugin-transform-react-inline-elements": "^7.10.4",
"@babel/plugin-transform-runtime": "^7.11.0",
"@babel/preset-env": "^7.11.0",
"@babel/preset-react": "^7.10.4",
"@babel/preset-typescript": "^7.10.4",
Expand Down Expand Up @@ -333,7 +340,8 @@
"shortid": "^2.2.15",
"socket.io": "^2.3.0",
"socket.io-client": "^2.3.0",
"source-map-support": "^0.5.19"
"source-map-support": "^0.5.19",
"winston": "^3.3.3"
},
"devEngines": {
"node": ">=7.x",
Expand Down Expand Up @@ -373,7 +381,8 @@
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
"pre-commit": "lint-staged",
"post-commit": "yarn coverage &> /dev/null && yarn sonar &> /dev/null &"
}
},
"jestSonar": {
Expand Down
6 changes: 3 additions & 3 deletions sonar-project.properties
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
sonar.projectKey=test-electron-react-boilerplate
# sonar.testExecutionReportPaths=test-reporter.xml
sonar.testExecutionReportPaths=test-reports/test-reporter.xml
sonar.typescript.lcov.reportPaths=coverage/lcov.info
sonar.sources=./app
sonar.tests=./test
sonar.coverage.exclusions=app/**/*.spec.ts,app/**/*.spec.tsx,app/**/*.test.ts,app/**/*.test.tsx,app/serviceWorker.ts,app/index.tsx
sonar.sources=app
sonar.tests=test
sonar.host.url=http://localhost:9000
sonar.login=d0c254aaff5ebd89dd5c6f0663238ab6ad5fddea
sonar.exclusions=app/client/**
Expand Down
18 changes: 18 additions & 0 deletions test/integration/app/server/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import http from 'http';
import SignalingServer from '../../../../app/server/index';

describe('signaling server', () => {
let server: typeof SignalingServer;
beforeEach(() => {
server = SignalingServer;
});

afterEach(() => {
server.stop();
});

it('start() should return http.Server', async () => {
const res = await server.start();
expect(res instanceof http.Server).toBe(true);
});
});
Loading

0 comments on commit 9856f41

Please sign in to comment.