From d2af14c45f499cc89e9fd44327008be8b356b105 Mon Sep 17 00:00:00 2001 From: Illya Gerasymchuk Date: Tue, 30 Jul 2024 20:28:16 +0100 Subject: [PATCH] feat: replace console.log() with logger. --- scripts/manage.ts | 6 ++++-- src/bot.ts | 21 ++++++++++--------- .../admin/screens/FundingRoundLogic.ts | 5 +++-- .../screens/ManageFundingRoundsScreen.ts | 4 +++- .../admin/screens/ManageSMEGroupsScreen.ts | 15 ++++++------- .../admin/screens/ManageTopicLogicScreen.ts | 21 ++++++++++--------- .../CommitteeDeliberationHomeScreen.ts | 1 + src/commands/checkChannels.ts | 11 +++++----- src/core/BaseClasses.ts | 13 ++++++------ src/models/index.ts | 5 +++-- src/setup/channelSetup.ts | 8 ++++--- src/types/index.ts | 2 +- 12 files changed, 63 insertions(+), 49 deletions(-) diff --git a/scripts/manage.ts b/scripts/manage.ts index c79c2ba..5d49417 100644 --- a/scripts/manage.ts +++ b/scripts/manage.ts @@ -6,6 +6,8 @@ import { initializeDatabase } from '../src/database'; import { addAdmin, removeAdmin } from '../src/database/admin'; import { checkRequiredChannels } from '../src/commands/checkChannels'; +import logger from '../src/logging'; + dotenv.config(); const client: Client = new Client({ @@ -18,11 +20,11 @@ async function main(): Promise { yargs(hideBin(process.argv)) .command('addAdmin ', 'Add an admin', {}, async (argv): Promise => { await addAdmin(argv.discordUserId as string); - console.log(`Admin added: ${argv.discordUserId}`); + logger.info(`Admin added: ${argv.discordUserId}`); }) .command('removeAdmin ', 'Remove an admin', {}, async (argv): Promise => { await removeAdmin(argv.discordUserId as string); - console.log(`Admin removed: ${argv.discordUserId}`); + logger.info(`Admin removed: ${argv.discordUserId}`); }) .command('checkChannels', 'Check required channels', {}, async (): Promise => { await client.login(process.env.DISCORD_TOKEN); diff --git a/src/bot.ts b/src/bot.ts index ee3d769..af3186a 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -15,6 +15,7 @@ import { CommitteeDeliberationDashboard } from './channels/deliberate/CommitteeD import { CommitteeDeliberationHomeScreen } from './channels/deliberate/CommitteeDeliberationHomeScreen'; import { ConsiderDashboard } from './channels/consider/ConsiderDashboard'; import { ConsiderationHomeScreen } from './channels/consider/screens/ConsiderationHomeScreen'; +import logger from './logging'; config(); @@ -25,7 +26,7 @@ const client = new Client({ const dashboardManager = new DashboardManager(); client.once('ready', async () => { - console.log('Bot is ready!'); + logger.info('Bot is ready!'); await syncDatabase(); // Register dashboards @@ -68,7 +69,7 @@ client.once('ready', async () => { if (adminChannel) { await adminDashboard.homeScreen.renderToTextChannel(adminChannel); } else { - console.error('Admin channel not found'); + logger.error('Admin channel not found'); } // Render initial screen in #funding-round-init channel @@ -76,7 +77,7 @@ client.once('ready', async () => { if (fundingRoundInitChannel) { await fundingRoundInitDashboard.homeScreen.renderToTextChannel(fundingRoundInitChannel); } else { - console.error('Funding Round Init channel not found'); + logger.error('Funding Round Init channel not found'); } @@ -85,7 +86,7 @@ client.once('ready', async () => { if (proposeChannel) { await proposeDashboard.homeScreen.renderToTextChannel(proposeChannel); } else { - console.error('Propose channel not found'); + logger.error('Propose channel not found'); } // Render initial screen in #vote channel @@ -93,7 +94,7 @@ client.once('ready', async () => { if (voteChannel) { await voteDashboard.homeScreen.renderToTextChannel(voteChannel); } else { - console.error('Vote channel not found'); + logger.error('Vote channel not found'); } // Render initial screen in #deliberate channel @@ -101,7 +102,7 @@ client.once('ready', async () => { if (deliberateChannel) { await committeeDeliberationDashboard.homeScreen.renderToTextChannel(deliberateChannel); } else { - console.error('Deliberate channel not found'); + logger.error('Deliberate channel not found'); } // Render initial screen in #consider channel @@ -109,11 +110,11 @@ client.once('ready', async () => { if (considerChannel) { await considerDashboard.homeScreen.renderToTextChannel(considerChannel); } else { - console.error('Consider channel not found'); + logger.error('Consider channel not found'); } } else { - console.error('No guild found'); + logger.error('No guild found'); } // Register other dashboards here @@ -123,13 +124,13 @@ client.on('interactionCreate', async (interaction: Interaction) => { try { if (!interaction.isButton() && !interaction.isStringSelectMenu() && !interaction.isModalSubmit() && !interaction.isMessageComponent()){ - console.log(`Interaction type not supported: ${interaction.type}`); + logger.info(`Interaction type not supported: ${interaction.type}`); return; } await dashboardManager.handleInteraction(interaction); } catch (error) { - console.error(error); + logger.error(error); } }); diff --git a/src/channels/admin/screens/FundingRoundLogic.ts b/src/channels/admin/screens/FundingRoundLogic.ts index ea2800e..7dee708 100644 --- a/src/channels/admin/screens/FundingRoundLogic.ts +++ b/src/channels/admin/screens/FundingRoundLogic.ts @@ -1,4 +1,5 @@ import sequelize from '../../../config/database'; +import logger from '../../../logging'; import { FundingRound, Topic, ConsiderationPhase, DeliberationPhase, FundingVotingPhase, SMEGroup, SMEGroupMembership, FundingRoundDeliberationCommitteeSelection, FundingRoundApprovalVote, TopicSMEGroupProposalCreationLimiter, Proposal } from '../../../models'; import { FundingRoundAttributes, FundingRoundStatus, FundingRoundPhase, ProposalStatus } from '../../../types'; import { Op, Transaction } from 'sequelize'; @@ -214,7 +215,7 @@ export class FundingRoundLogic { insertedCount++; } } catch (error) { - console.error('Error in appendFundingRoundCommitteeMembers:', error); + logger.error('Error in appendFundingRoundCommitteeMembers:', error); } } @@ -265,7 +266,7 @@ export class FundingRoundLogic { return count; } catch (error) { - console.error('Error in countSMEMembersInDeliberationCommittee:', error); + logger.error('Error in countSMEMembersInDeliberationCommittee:', error); throw error; } } diff --git a/src/channels/admin/screens/ManageFundingRoundsScreen.ts b/src/channels/admin/screens/ManageFundingRoundsScreen.ts index ac7f9b8..2259e18 100644 --- a/src/channels/admin/screens/ManageFundingRoundsScreen.ts +++ b/src/channels/admin/screens/ManageFundingRoundsScreen.ts @@ -7,6 +7,8 @@ import { InteractionProperties } from '../../../core/Interaction'; import { PaginationComponent } from '../../../components/PaginationComponent'; import { FundingRoundPhase } from '../../../types'; import { TopicLogic } from './ManageTopicLogicScreen'; +import logger from '../../../logging'; + export class ManageFundingRoundsScreen extends Screen { public static readonly ID = 'manageFundingRounds'; @@ -787,7 +789,7 @@ export class ModifyFundingRoundAction extends Action { const startDateValue: string = phase === 'round' && fundingRound.startAt ? this.formatDate(fundingRound.startAt) : existingPhase ? this.formatDate(existingPhase.startDate) : ''; const endDateValue: string = phase === 'round' && fundingRound.startAt ? this.formatDate(fundingRound.endAt) : existingPhase ? this.formatDate(existingPhase.endDate) : ''; - console.log(`startDateValue: ${startDateValue} endDateValue: ${endDateValue}`); + logger.info(`startDateValue: ${startDateValue} endDateValue: ${endDateValue}`); const modal = new ModalBuilder() .setCustomId(CustomIDOracle.addArgumentsToAction(this, ModifyFundingRoundAction.OPERATIONS.SUBMIT_PHASE, 'fundingRoundId', fundingRoundId, 'phase', phase)) diff --git a/src/channels/admin/screens/ManageSMEGroupsScreen.ts b/src/channels/admin/screens/ManageSMEGroupsScreen.ts index 33c8438..5465924 100644 --- a/src/channels/admin/screens/ManageSMEGroupsScreen.ts +++ b/src/channels/admin/screens/ManageSMEGroupsScreen.ts @@ -8,6 +8,7 @@ import { AnyInteraction, AnyInteractionWithValues, AnyModalMessageComponent } fr import { PaginationComponent } from '../../../components/PaginationComponent'; import { PaginationLogic } from '../../../utils/Pagination'; import { InteractionProperties } from '../../../core/Interaction'; +import logger from '../../../logging'; export class SMEGroupLogic { @@ -409,7 +410,7 @@ class AddSMEGroupAction extends Action { const successMessage = `✅ SME Group '${name}' created successfully`; await this.screen.reRender(interaction, { successMessage: successMessage }); } catch (err) { - console.error(err); + logger.error(err); const errorMessage = `🚫 An error occurred while creating the group '${name}'`; await this.screen.reRender(interaction, { errorMessage: errorMessage }); } @@ -503,7 +504,7 @@ class RemoveSMEGroupAction extends Action { ephemeral: true }); } catch (error) { - console.error('Error fetching group details:', error); + logger.error('Error fetching group details:', error); await interaction.respond({ content: 'An error occurred while fetching group details. Please try again later.', ephemeral: true }); } } @@ -520,7 +521,7 @@ class RemoveSMEGroupAction extends Action { const successMessage = 'SME Group has been successfully removed along with all its dependencies.'; await this.screen.render(interaction, { successMessage }); } catch (error) { - console.error('Error removing SME Group:', error); + logger.error('Error removing SME Group:', error); const errorMessage = 'An error occurred while removing the SME Group. Please try again later.'; await this.screen.render(interaction, { errorMessage }); } @@ -562,7 +563,7 @@ class ManageMembersAction extends PaginationComponent { } protected async handleOperation(interaction: TrackedInteraction, operationId: string): Promise { - console.log(`Handling operation ${operationId} on ${interaction.customId}`); + logger.info(`Handling operation ${operationId} on ${interaction.customId}`); switch (operationId) { case ManageMembersAction.Operations.VIEW_MEMBERS: @@ -605,7 +606,7 @@ class ManageMembersAction extends PaginationComponent { const successMessage = `Successfully removed ${removedCount} member(s) from the group.`; await this.handleViewMembers(interaction, successMessage); } catch (error) { - console.error('Error removing members from group:', error); + logger.error('Error removing members from group:', error); const errorMessage = 'An error occurred while removing members from the group. Please try again later.'; await this.screen.reRender(interaction, { errorMessage }); } @@ -669,7 +670,7 @@ class ManageMembersAction extends PaginationComponent { } private async handleAddMembers(interaction: TrackedInteraction): Promise { - console.log('Handling add members...'); + logger.info('Handling add members...'); const groupId = CustomIDOracle.getNamedArgument(interaction.customId, 'groupId'); if (!groupId) { await interaction.respond({ content: 'Invalid group ID.', ephemeral: true }); @@ -711,7 +712,7 @@ class ManageMembersAction extends PaginationComponent { const successMessage = `Successfully added ${result.added} member(s) to the group. ${result.skipped} member(s) were already in the group and skipped.`; await this.handleViewMembers(interaction, successMessage); } catch (error) { - console.error('Error adding members to group:', error); + logger.error('Error adding members to group:', error); const errorMessage = 'An error occurred while adding members to the group. Please try again later.'; await this.screen.reRender(interaction, { errorMessage }); } diff --git a/src/channels/admin/screens/ManageTopicLogicScreen.ts b/src/channels/admin/screens/ManageTopicLogicScreen.ts index df5d72d..da71954 100644 --- a/src/channels/admin/screens/ManageTopicLogicScreen.ts +++ b/src/channels/admin/screens/ManageTopicLogicScreen.ts @@ -8,6 +8,7 @@ import { TopicAttributes, TopicCommitteeAttributes } from '../../../types'; import { allowedNodeEnvironmentFlags } from 'process'; import { InteractionProperties } from '../../../core/Interaction'; import { parsed } from 'yargs'; +import logger from '../../../logging'; interface TopicCommitteeWithSMEGroup extends TopicCommitteeAttributes { smeGroupName: string; @@ -610,7 +611,7 @@ class AddTopicAction extends Action { const successMessage = `✅ Topic '${name}' created successfully`; await this.screen.reRender(interaction, { successMessage: successMessage }); } catch (err) { - console.error(err); + logger.error(err); const errorMessage = `🚫 An error occurred while creating the topic '${name}': ${(err as Error).message}`; await interaction.respond({ content: errorMessage, ephemeral: true }); } @@ -712,7 +713,7 @@ class RemoveTopicAction extends Action { ephemeral: true }); } catch (error) { - console.error('Error fetching topic details:', error); + logger.error('Error fetching topic details:', error); await interaction.respond({ content: 'An error occurred while fetching topic details. Please try again later.', ephemeral: true }); } } @@ -729,7 +730,7 @@ class RemoveTopicAction extends Action { const successMessage = 'Topic has been successfully removed.'; await this.screen.render(interaction, { successMessage }); } catch (error) { - console.error('Error removing Topic:', error); + logger.error('Error removing Topic:', error); const errorMessage = 'An error occurred while removing the Topic. Please try again later.'; await this.screen.render(interaction, { errorMessage }); } @@ -872,7 +873,7 @@ class EditTopicAction extends Action { const successMessage = `✅ Topic '${name}' updated successfully`; await this.screen.reRender(interaction, { successMessage: successMessage }); } catch (err) { - console.error(err); + logger.error(err); const errorMessage = `🚫 An error occurred while updating the topic '${name}': ${(err as Error).message}`; await this.screen.reRender(interaction, { errorMessage: errorMessage }); } @@ -1200,9 +1201,9 @@ export class CommitteePaginationAction extends PaginationComponent { const topicId = topicIdFromCustomId ? topicIdFromCustomId : topicIdFromContext; - console.log('topicIdFromCustomId:', topicIdFromCustomId); - console.log('topicIdFromContext:', topicIdFromContext); - console.log('topicId:', topicId); + logger.info('topicIdFromCustomId:', topicIdFromCustomId); + logger.info('topicIdFromContext:', topicIdFromContext); + logger.info('topicId:', topicId); if (!topicId) { @@ -1214,9 +1215,9 @@ export class CommitteePaginationAction extends PaginationComponent { const totalPages = await this.getTotalPages(interaction); const committees = await this.getItemsForPage(interaction, currentPage); - console.log('currentPage:', currentPage); - console.log('totalPages:', totalPages); - console.log('committees:', committees); + logger.info('currentPage:', currentPage); + logger.info('totalPages:', totalPages); + logger.info('committees:', committees); const embed = new EmbedBuilder() .setColor('#0099ff') diff --git a/src/channels/deliberate/CommitteeDeliberationHomeScreen.ts b/src/channels/deliberate/CommitteeDeliberationHomeScreen.ts index 73b0d30..a47539d 100644 --- a/src/channels/deliberate/CommitteeDeliberationHomeScreen.ts +++ b/src/channels/deliberate/CommitteeDeliberationHomeScreen.ts @@ -1,3 +1,4 @@ +// src/channels/deliberate/CommitteeDeliberationHomeScreen.ts import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, MessageActionRowComponentBuilder, ModalBuilder, StringSelectMenuBuilder, TextChannel, TextInputBuilder, TextInputStyle } from 'discord.js'; import { CommitteeDeliberationLogic } from '../../logic/CommitteeDeliberationLogic'; import { IHomeScreen } from '../../types/common'; diff --git a/src/commands/checkChannels.ts b/src/commands/checkChannels.ts index 7cbb91c..8d533ea 100644 --- a/src/commands/checkChannels.ts +++ b/src/commands/checkChannels.ts @@ -1,11 +1,12 @@ import { Client, Guild, ChannelType, CategoryChannel } from 'discord.js'; import { CONSTANTS } from '../constants'; +import logger from '../logging'; export async function checkRequiredChannels(client: Client): Promise { const guild: Guild | undefined = client.guilds.cache.get(process.env.GUILD_ID!); if (!guild) { - console.error(`${CONSTANTS.EMOJIS.ERROR} Guild not found`); + logger.error(`${CONSTANTS.EMOJIS.ERROR} Guild not found`); return; } @@ -14,11 +15,11 @@ export async function checkRequiredChannels(client: Client): Promise { ) as CategoryChannel | undefined; if (!govbotCategory) { - console.log(`${CONSTANTS.EMOJIS.ERROR} 'govbot' category not found`); + logger.info(`${CONSTANTS.EMOJIS.ERROR} 'govbot' category not found`); return; } - console.log(`${CONSTANTS.EMOJIS.SUCCESS} 'govbot' category found`); + logger.info(`${CONSTANTS.EMOJIS.SUCCESS} 'govbot' category found`); const requiredChannels: string[] = Object.values(CONSTANTS.CHANNELS); @@ -28,9 +29,9 @@ export async function checkRequiredChannels(client: Client): Promise { ); if (channel) { - console.log(`${CONSTANTS.EMOJIS.SUCCESS} '${channelName}' channel found in 'govbot' category`); + logger.info(`${CONSTANTS.EMOJIS.SUCCESS} '${channelName}' channel found in 'govbot' category`); } else { - console.log(`${CONSTANTS.EMOJIS.ERROR} '${channelName}' channel not found in 'govbot' category`); + logger.info(`${CONSTANTS.EMOJIS.ERROR} '${channelName}' channel not found in 'govbot' category`); } } } \ No newline at end of file diff --git a/src/core/BaseClasses.ts b/src/core/BaseClasses.ts index 85a2bde..641aecf 100644 --- a/src/core/BaseClasses.ts +++ b/src/core/BaseClasses.ts @@ -4,6 +4,7 @@ import { InteractionResponse, Message, MessageComponentInteraction } from 'disco import { CustomIDOracle } from '../CustomIDOracle'; import { AnyModalMessageComponent, AnyInteraction, HomeScreen } from '../types/common'; import { InteractionProperties } from './Interaction'; +import logger from '../logging'; export interface RenderArgs { successMessage?: string, @@ -47,7 +48,7 @@ export class TrackedInteraction { } } catch (error) { - console.log('Error in respond: ', error); + logger.info('Error in respond: ', error); throw error; } } @@ -206,7 +207,7 @@ export abstract class Screen { try { await interaction.respond(responseArgs); } catch (error) { - console.log('Error in render: ', error); + logger.info('Error in render: ', error); } return; } @@ -221,7 +222,7 @@ export abstract class Screen { await interaction.respond(responseArgs); } } catch (error) { - console.log('Error in re-render:\n', error); + logger.info('Error in re-render:\n', error); } } @@ -296,8 +297,8 @@ export abstract class Screen { public registerAction(action: Action, actionId: string): void { this.actions.set(actionId, action); - //console.log(`Action registered: ${actionId}`); - //console.log(action); + //logger.info(`Action registered: ${actionId}`); + //logger.info(action); } } @@ -330,7 +331,7 @@ export abstract class Dashboard { throw new Error('Home screen not set.'); } - console.log("[Dashboard] Handling interaction ", interaction.customId); + logger.info("[Dashboard] Handling interaction ", interaction.customId); const screenId = CustomIDOracle.getScreenId(interaction.customId); if (!screenId) { diff --git a/src/models/index.ts b/src/models/index.ts index 3887573..24a177e 100644 --- a/src/models/index.ts +++ b/src/models/index.ts @@ -44,6 +44,7 @@ import { SMEGroupMembershipAttributes, SMEGroupMembershipCreationAttributes, } from '../types'; +import logger from '../logging'; const sequelize: Sequelize = new Sequelize({ dialect: 'sqlite', @@ -996,9 +997,9 @@ export { export const syncDatabase = async (): Promise => { try { await sequelize.sync(); - console.log('Database synced successfully'); + logger.info('Database synced successfully'); } catch (error) { - console.error('Error syncing database:', error); + logger.error('Error syncing database:\n', error); } }; diff --git a/src/setup/channelSetup.ts b/src/setup/channelSetup.ts index 121c22c..f5fd6fd 100644 --- a/src/setup/channelSetup.ts +++ b/src/setup/channelSetup.ts @@ -1,10 +1,12 @@ import { Client, TextChannel, ChannelType, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, CategoryChannel } from 'discord.js'; import { CONSTANTS } from '../constants'; +import logger from '../logging'; + export async function setupAdminChannel(client: Client): Promise { const guild = client.guilds.cache.get(process.env.GUILD_ID!); if (!guild) { - console.error('Guild not found'); + logger.error('Guild not found'); return; } @@ -13,7 +15,7 @@ export async function setupAdminChannel(client: Client): Promise { ) as CategoryChannel | undefined; if (!govbotCategory) { - console.error(`${CONSTANTS.EMOJIS.ERROR} 'govbot' category not found`); + logger.error(`${CONSTANTS.EMOJIS.ERROR} 'govbot' category not found`); return; } @@ -22,7 +24,7 @@ export async function setupAdminChannel(client: Client): Promise { ) as TextChannel | undefined; if (!adminChannel) { - console.error(`${CONSTANTS.EMOJIS.ERROR} 'admin' channel not found in 'govbot' category`); + logger.error(`${CONSTANTS.EMOJIS.ERROR} 'admin' channel not found in 'govbot' category`); return; } diff --git a/src/types/index.ts b/src/types/index.ts index db758f8..7ceef9e 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -210,7 +210,7 @@ export interface FundingRoundApprovalVoteCreationAttributes extends Optional