Skip to content

Commit

Permalink
Merge pull request #10 from GitStartHQ/gitstart-error-logs
Browse files Browse the repository at this point in the history
Show errors in the Main Window
  • Loading branch information
ziahamza authored Jun 8, 2021
2 parents b0e3987 + ebd1d98 commit 73fa7c8
Show file tree
Hide file tree
Showing 10 changed files with 192 additions and 4 deletions.
63 changes: 63 additions & 0 deletions client/src/components/Settings/LogList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import React, { useEffect, useState } from 'react';
import { Alert } from 'antd';
import { findAllLogs } from '../../services/logs-api';
import moment from 'moment';

type Log = {
id: number;
createdAt: Date;
updatedAt: Date;
type: 'ERROR';
message?: string;
jsonData?: string;
};

export const LogList = () => {
const [logs, setLogs] = useState<Log[]>([]);

const getAllLogs = async () => {
const newLogs = await findAllLogs(
moment()
.subtract(1, 'day')
.toDate(),
);
setLogs(newLogs);
};

const handleDismiss = () => {
// TODO: handle dismissing of logs
};

useEffect(() => {
if (logs.length === 0) {
getAllLogs();
}
const toCancel = setTimeout(() => {
getAllLogs();
}, 10000);

return () => clearTimeout(toCancel);
// eslint-disable-next-line
}, []);

if (logs.length === 0) {
return null;
}

return (
<>
{logs.map(log => (
<Alert
type={log.type === 'ERROR' ? 'error' : 'warning'}
message={`"${log.message}" ${moment(log.updatedAt).fromNow()}`}
description={`${JSON.stringify(log.jsonData)} | Created at: ${moment(
log.createdAt,
).format()}`}
closeText="Dismiss"
onClose={handleDismiss}
style={{ marginBottom: '16px' }}
/>
))}
</>
);
};
22 changes: 19 additions & 3 deletions client/src/components/Settings/LoginForm.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import { Button, Card, Typography } from 'antd';
import { loginInExternalBrowser } from '../../services/settings.api';
import { fetchLoginSettings, loginInExternalBrowser } from '../../services/settings.api';

const { Text } = Typography;

export const LoginForm = () => {
// FIXME: This is duplicate code from client/src/components/MainLayout/MainLayout.tsx. Replace with a store to avoid fetching the same thing twice.
const [isLoggedIn, setIsLoggedIn] = useState(false); // avoid first render where alert is shown

const checkLoginSettings = async () => {
const settings = await fetchLoginSettings();
if (!settings) return;

if (settings.token) {
setIsLoggedIn(true);
}
};

useEffect(() => {
checkLoginSettings();
}, []);

return (
<Card title="Login">
<Button type="primary" block size="large" onClick={loginInExternalBrowser}>
Login to GitStart
Login {isLoggedIn ? 'Again' : 'to GitStart'}
</Button>
<Text type="secondary">
You must alreay have a GitStart account to login through here. Create an account at{' '}
Expand Down
4 changes: 4 additions & 0 deletions client/src/components/Settings/SettingsForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { AppForm } from './AppForm';
import { WorkForm } from './WorkForm';
import { LoginForm } from './LoginForm';
import { ThemeSelect } from './ThemeSelect';
import { LogList } from './LogList';

export const SettingsForm = () => {
return (
Expand All @@ -27,6 +28,9 @@ export const SettingsForm = () => {
{/* <Box p={1}>
<AnalyserForm />
</Box> */}
<Box p={1}>
<LogList />
</Box>
</Box>
</Flex>
</Form>
Expand Down
9 changes: 9 additions & 0 deletions client/src/services/logs-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { emit } from 'eiphop';

export async function findAllLogs(from: Date, to?: Date) {
const data = await emit('findAllLogs', {
from,
to,
});
return data;
}
11 changes: 10 additions & 1 deletion electron/app/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { trackItemService } from './services/track-item-service';
import { stateManager } from './state-manager';
import { State } from './enums/state';
import { appConstants } from './app-constants';
import { logService } from './services/log-service';

const settingsActions = {
fetchAnalyserSettingsJsonString: async (req, res) => {
Expand Down Expand Up @@ -42,6 +43,14 @@ const appSettingsActions = {
res.send(data);
},
};

const logsActions = {
findAllLogs: async ({ payload }, res) => {
const data = await logService.findAllLogs(payload.from, payload.to);
res.send(data);
},
};

const trackItemActions = {
findAllDayItems: async ({ payload }, res) => {
const data = await trackItemService.findAllDayItems(
Expand Down Expand Up @@ -96,6 +105,6 @@ const trackItemActions = {
export const initIpcActions = () =>
setupMainHandler(
{ ipcMain } as any,
{ ...settingsActions, ...appSettingsActions, ...trackItemActions },
{ ...settingsActions, ...appSettingsActions, ...logsActions, ...trackItemActions },
true,
);
2 changes: 2 additions & 0 deletions electron/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import AppUpdater from './app-updater';
import config from './config';
import { appConstants } from './app-constants';
import { settingsService } from './services/settings-service';
import { logService } from './services/log-service';
import moment = require('moment');

let logger = logManager.getLogger('AppIndex');
app.setAppUserModelId(process.execPath);
Expand Down
8 changes: 8 additions & 0 deletions electron/app/jobs/save-to-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { appConstants } from '../app-constants';
import { fetchGraphQLClient, getUserFromToken } from '../graphql';
import { logManager } from '../log-manager';
import { TrackItem } from '../models/TrackItem';
import { logService } from '../services/log-service';
import { settingsService } from '../services/settings-service';
import { trackItemService } from '../services/track-item-service';

Expand Down Expand Up @@ -172,6 +173,13 @@ export class SaveToDbJob {
console.log('Successfully linked', items.length, `user_event with its TrackItem`);
} catch (e) {
console.error(e);
logService
.createOrUpdateLog({
type: 'ERROR',
message: e.message,
jsonData: JSON.stringify(e),
})
.catch(console.error);
}
}
}
Expand Down
20 changes: 20 additions & 0 deletions electron/app/models/Log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Model } from 'objection';

/**
* This Log model will primarily be used to keep track of all errors in the DevTime app.
* This table can be extended to also keep track of other kinds of logs. Things that don't need to be saved to GitStart's database.
*/
export class Log extends Model {
static tableName = 'Logs';

id!: number;
createdAt!: Date;
updatedAt!: Date;
type!: 'ERROR';
message?: string;
jsonData?: any;

static get jsonAttributes() {
return ['jsonData'];
}
}
43 changes: 43 additions & 0 deletions electron/app/services/log-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { logManager } from '../log-manager';
import { Log } from '../models/Log';

export class LogService {
logger = logManager.getLogger('LogService');
lastLog: null | Log = null;

async createOrUpdateLog(logAttributes: Partial<Log>): Promise<Log> {
let log: Log = null;
if (
this.lastLog &&
logAttributes.type === this.lastLog.type &&
logAttributes.message === this.lastLog.message &&
logAttributes.jsonData === this.lastLog.jsonData
) {
const now = new Date();
await Log.query().findById(this.lastLog.id).patch({
updatedAt: now,
});
log = this.lastLog;
log.updatedAt = now;
} else {
logAttributes.createdAt = new Date();
logAttributes.updatedAt = new Date();
log = await Log.query().insert(logAttributes);
}
this.lastLog = log;
return log;
}

async findAllLogs(from: Date, to?: Date) {
if (!to) {
to = new Date();
}
return Log.query()
.where('updatedAt', '>=', from)
.where('updatedAt', '<=', to)
.skipUndefined()
.orderBy('updatedAt', 'DESC');
}
}

export const logService = new LogService();
14 changes: 14 additions & 0 deletions electron/migrations/20210607180611_create-Logs-table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
exports.up = function (knex) {
return knex.schema.createTable('Logs', (table) => {
table.increments('id').notNullable();
table.dateTime('createdAt').notNullable();
table.dateTime('updatedAt').notNullable();
table.string('type').notNullable();
table.string('message');
table.string('jsonData');
});
};

exports.down = function (knex) {
return knex.schema.dropTable('Logs');
};

0 comments on commit 73fa7c8

Please sign in to comment.