Skip to content

Commit

Permalink
Improve server logging (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewjamesadam authored Apr 16, 2021
1 parent 003a178 commit e6d9a47
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 27 deletions.
3 changes: 2 additions & 1 deletion server/Bot.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BotTarget, ChannelModel, PersonModel } from './Db';
import { GameManagerProvider } from './GameManager';
import { Logger } from './Logger';

enum MessageStyle {
normal,
Expand Down Expand Up @@ -201,7 +202,7 @@ export abstract class Bot implements IBot {
if (error instanceof GameLogicError) {
this.sendMessage(channel, ...error.messageContent);
} else {
console.log(error);
Logger.exception(error);
this.printIDunnoMessage(channel);
}
}
Expand Down
3 changes: 2 additions & 1 deletion server/DiscordBot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Bot, PersonAvatar, PersonRef } from './Bot';
import { BotTarget, ChannelModel, PersonModel } from './Db';
import { GameManagerProvider } from './GameManager';
import Express from 'express';
import { Logger } from './Logger';

export class DiscordBot extends Bot {
client: Discord.Client;
Expand All @@ -19,7 +20,7 @@ export class DiscordBot extends Bot {
}

this.client.on('error', (err) => {
console.log(err);
Logger.exception(err);
});

this.client.on('message', (message) => {
Expand Down
5 changes: 1 addition & 4 deletions server/EpycApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,7 @@ export class EpycApi extends EpycApiBase {
}

private logError(error: Error) {
console.log(`Caught error: ${error}`);
if (error.stack) {
console.log(error.stack);
}
console.error(error);
}

async getFramePlayData(params: GetFramePlayDataParams, context: Context): Promise<FramePlayData> {
Expand Down
5 changes: 3 additions & 2 deletions server/GameManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { RandomEmoji } from './Emojis';
import { v4 as uuid } from 'uuid';
import ArrayUtils from './Utils';
import Utils from './Utils';
import { Logger } from './Logger';

// Cheap IOC container
export class GameManagerProvider {
Expand Down Expand Up @@ -132,7 +133,7 @@ export class GameManager {
const frames: Array<FrameModel> = allPersons.map((person) => FrameModel.create(person.id));

// FIXME -- for dev testing -- remove at some point!
if (!Cfg.isProduction) {
if (!Cfg.isProduction && frames.length > 0) {
while (frames.length < 4) {
frames.push(FrameModel.create(frames[0].personId));
}
Expand All @@ -149,7 +150,7 @@ export class GameManager {
try {
await this.db.putGame(game);
} catch (error) {
console.log(error);
Logger.exception(error);
throw new GameLogicError('Could not create game');
}

Expand Down
23 changes: 23 additions & 0 deletions server/Logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
Centralized logging. For now this just goes to the console.
*/
export class Logger {
static log(message: string) {
console.log(message);
}

static error(message: string) {
console.error(message);
}

static exception(error: any, message?: string) {
if (message) {
console.error(message);
}

console.error(error);
if (error.stack) {
console.error(error.stack);
}
}
}
41 changes: 33 additions & 8 deletions server/SlackBot.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SocketModeClient } from '@slack/socket-mode';
import { WebClient } from '@slack/web-api';
import { WebAPICallResult, WebClient } from '@slack/web-api';
import { InstallProvider } from '@slack/oauth';
import { createEventAdapter, SlackEventAdapter } from '@slack/events-api';
import { Bot, PersonAvatar, PersonRef } from './Bot';
Expand All @@ -10,6 +10,7 @@ import { RequestListener } from 'http';
import { v4 as uuid } from 'uuid';
import Express from 'express';
import Utils from './Utils';
import { Logger } from './Logger';

const RE_TAG = new RegExp('<@(.+?)>', 'g');

Expand Down Expand Up @@ -60,7 +61,7 @@ export class SlackBot extends Bot {
},
});
} else {
console.log('SLACK_CLIENT_ID or SLACK_CLIENT_SECRET is undefined -- slack oauth disabled.');
Logger.log('SLACK_CLIENT_ID or SLACK_CLIENT_SECRET is undefined -- slack oauth disabled.');
}

if (Cfg.slackUseSocketApi) {
Expand All @@ -70,7 +71,7 @@ export class SlackBot extends Bot {
// }

if (!token) {
console.log('SLACK_SOCKET_TOKEN is undefined');
Logger.log('SLACK_SOCKET_TOKEN is undefined');
return;
}

Expand All @@ -94,7 +95,7 @@ export class SlackBot extends Bot {
// }

if (!signingSecret) {
console.log('SLACK_REQUEST_SIGNING_SECRET is undefined');
Logger.log('SLACK_REQUEST_SIGNING_SECRET is undefined');
return;
}

Expand All @@ -108,7 +109,7 @@ export class SlackBot extends Bot {
}

// this.client.on('error', (err) => {
// console.log(err);
// Logger.exception(err);
// });
}

Expand Down Expand Up @@ -226,11 +227,13 @@ export class SlackBot extends Bot {

const teamToken = await this.getTeamToken(teamId);
if (!teamToken) {
Logger.error(`No token available for team ${teamId} -- cannot process incoming message`);
return;
}

const authorPerson = await this.resolvePersonRef(teamId, teamToken, authorId);
if (!authorPerson) {
Logger.error(`Cannot resolve author for event ${teamId} ${authorId}`);
return;
}

Expand Down Expand Up @@ -270,10 +273,15 @@ export class SlackBot extends Bot {

const token = await this.getTeamToken(teamId);
if (!token) {
Logger.error(`No token available for team ${teamId} -- cannot send message to channel ${channel.id}`);
return;
}

await this.webClient.chat.postMessage({ token, text: content, channel: channelId });
try {
await this.webClient.chat.postMessage({ token, text: content, channel: channelId });
} catch (error) {
Logger.exception(error, `Could not send message to channel ${channel.id}`);
}
}

protected async sendStringDM(person: PersonModel, content: string): Promise<void> {
Expand All @@ -284,10 +292,15 @@ export class SlackBot extends Bot {

const token = await this.getTeamToken(teamId);
if (!token) {
Logger.error(`No token available for team ${teamId} -- cannot send DM to ${person.name} ${person.id}`);
return;
}

await this.webClient.chat.postMessage({ token, text: content, channel: userId });
try {
await this.webClient.chat.postMessage({ token, text: content, channel: userId });
} catch (error) {
Logger.exception(error, `Could not send DM to ${person.name} ${person.id}`);
}
}

protected toBold(content: string): string {
Expand All @@ -306,10 +319,22 @@ export class SlackBot extends Bot {

const token = await this.getTeamToken(teamId);
if (!token) {
Logger.error(
`No token available for team ${teamId} -- cannot get avatar for person ${person.name} ${person.id}`
);
return;
}

const user = await this.webClient.users.info({ token, user: userId });
let user: WebAPICallResult;
try {
user = await this.webClient.users.info({ token, user: userId });
} catch (error) {
Logger.exception(
error,
`Could not get information for person ${person.name} ${person.id} -- cannot get avatar`
);
return;
}

if (user.ok) {
const profile: any = user['user'];
Expand Down
11 changes: 6 additions & 5 deletions server/sendNotifications.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
import { Db } from './Db';
import { DiscordBot } from './DiscordBot';
import { GameManager, GameManagerProvider } from './GameManager';
import { Logger } from './Logger';
import { SlackBot } from './SlackBot';

const startDiscord = async (gameManager: GameManagerProvider): Promise<DiscordBot> => {
console.log('*** Starting Discord Bot');
Logger.log('*** Starting Discord Bot');

let bot = new DiscordBot(gameManager);
await bot.init();
return bot;
};

let startSlack = async (db: Db, gameManager: GameManagerProvider): Promise<SlackBot> => {
console.log('*** Starting Slack Bot');
Logger.log('*** Starting Slack Bot');

let bot = new SlackBot(db, gameManager);
await bot.init();
return bot;
};

const startDb = async () => {
console.log('*** Starting Database');
Logger.log('*** Starting Database');

let db = Db.create();
return db;
Expand All @@ -35,9 +36,9 @@ const notify = async () => {

gameManagerProvider._gameManager = new GameManager(db, discordBot, slackBot);

console.log('*** Sending Notifications');
Logger.log('*** Sending Notifications');
await gameManagerProvider.gameManager.notifyPlayers();
console.log('*** Done Sending Notifications');
Logger.log('*** Done Sending Notifications');

await discordBot.deinit();
await db.deinit();
Expand Down
13 changes: 7 additions & 6 deletions server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,26 @@ import CookieParser from 'cookie-parser';
import { DiscordBot } from './DiscordBot';
import { GameManager, GameManagerProvider } from './GameManager';
import { SlackBot } from './SlackBot';
import { Logger } from './Logger';

let startDiscord = async (gameManager: GameManagerProvider): Promise<DiscordBot> => {
console.log('*** Starting Discord Bot');
Logger.log('*** Starting Discord Bot');

let bot = new DiscordBot(gameManager);
await bot.init();
return bot;
};

let startSlack = async (db: Db, gameManager: GameManagerProvider): Promise<SlackBot> => {
console.log('*** Starting Slack Bot');
Logger.log('*** Starting Slack Bot');

let bot = new SlackBot(db, gameManager);
await bot.init();
return bot;
};

let startDb = async () => {
console.log('*** Starting Database');
Logger.log('*** Starting Database');

let db = Db.create();
return db;
Expand All @@ -38,7 +39,7 @@ let startServer = async (
slackBot: SlackBot,
discordBot: DiscordBot
) => {
console.log('*** Starting Server');
Logger.log('*** Starting Server');

let corsDomains = new Set<string>(['http://epyc.phlegmatic.ca', 'https://epyc.phlegmatic.ca']);

Expand Down Expand Up @@ -103,7 +104,7 @@ let startServer = async (

app.listen(process.env.PORT || 3001);

console.log('*** Server Started');
Logger.log('*** Server Started');
};

let bootup = async () => {
Expand All @@ -117,7 +118,7 @@ let bootup = async () => {

gameManagerProvider._gameManager = new GameManager(db, discordBot, slackBot);
} catch (e) {
console.error(`Error occurred on startup: ${e}`);
Logger.exception(e, 'Error occurred on startup');
}
};

Expand Down

0 comments on commit e6d9a47

Please sign in to comment.