From d52899e9725667dd4771d9261ece2b5aab9260ec Mon Sep 17 00:00:00 2001 From: WhizBangPop Date: Mon, 28 Nov 2022 12:49:42 +0000 Subject: [PATCH] Added projectwide logger implamentation --- src/listeners/newCommandHandler.ts | 1 - src/listeners/onMessageCreate.ts | 10 ++++----- src/listeners/ready.ts | 28 +++++++++++------------- src/scripts/DiscordJS/clearCommands.ts | 9 ++++---- src/scripts/DiscordJS/manCommandLoad.ts | 9 ++++---- src/scripts/DiscordJS/syncCommands.ts | 9 ++++---- src/theHeart.ts | 17 +++++++-------- src/utilities.ts | 29 ++++++++++++------------- 8 files changed, 52 insertions(+), 60 deletions(-) diff --git a/src/listeners/newCommandHandler.ts b/src/listeners/newCommandHandler.ts index 613e2a3..255e83d 100644 --- a/src/listeners/newCommandHandler.ts +++ b/src/listeners/newCommandHandler.ts @@ -2,7 +2,6 @@ import { Client, Collection, GuildMember } from "discord.js" import { Client as SClient } from "statcord.js" import fs from "fs" import path from "path" -import { createSimpleLogger } from "simple-node-logger" import { QuickDB } from "quick.db" import { webhookReporter } from "../utilities" import { config } from "../../data/config" diff --git a/src/listeners/onMessageCreate.ts b/src/listeners/onMessageCreate.ts index 03484a3..6267230 100644 --- a/src/listeners/onMessageCreate.ts +++ b/src/listeners/onMessageCreate.ts @@ -14,7 +14,7 @@ import fs from "fs"; import { AsciiTable3, AlignmentEnum } from "ascii-table3"; // Node logger -const log = createSimpleLogger("./data/mcb.log"); +import { debug,log,error } from '../lib/tsabLogger'; // Automatic command importer const commandArray: Array = []; @@ -25,7 +25,7 @@ fs.readdirSync(commandDir).forEach(file => { file = file.toLowerCase(); if (file.startsWith('temp')) return; commandArray.push(file); - log.info(`Imported Command: ${file}`); + log(`Imported Command: ${file}`); }) const table = new AsciiTable3('Commands') @@ -95,7 +95,7 @@ export default (client: Client, statcord: SClient): void => { if (!member!.permissions.has(`${commandToRun.requiredPermissions[i]}`)) return msg.reply(config.responses.noPermission); } - log.info('Special command run!') + log('Special command run!') commandToRun.execute(msg, args, client); return statcord.postCommand(command, msg.author.id); } else { @@ -111,7 +111,7 @@ export default (client: Client, statcord: SClient): void => { } }); - client.on('error', async (error) => { - log.error(`OH F**K SOMETHING REALLY REALLY WENT WRONG. HERE'S THE RUNDOWN: \n\n${error}`) + client.on('error', async (e) => { + error(`SOMETHING REALLY REALLY WENT WRONG. HERE'S THE RUNDOWN: \n\n\`${e}\``, { sendWebhook:true }) }) }; diff --git a/src/listeners/ready.ts b/src/listeners/ready.ts index fb4f397..a883548 100644 --- a/src/listeners/ready.ts +++ b/src/listeners/ready.ts @@ -14,8 +14,7 @@ import Statcord from "statcord.js" import { REST } from "@discordjs/rest" import { Routes } from "discord-api-types/v10" -const log = createSimpleLogger("./data/mcb.log") -log.setLevel("debug") // set to INFO for production (i mean unless you want lots more info then go ahead lol) +import { debug,log,error } from '../lib/tsabLogger'; const db = new QuickDB() const sysInternals = db.table("sysInt") @@ -32,7 +31,7 @@ export default (client: Client, statcord: Statcord.Client): void => { checkForInfo() await statcord.autopost() - log.info(`${client.user.tag} connected to Discord Gateway successfully`) + log(`${client.user.tag} connected to Discord Gateway successfully`) const guild = client.guilds.cache.get(config.discord.serverId) const logChannel = guild?.channels.cache.get( @@ -41,14 +40,13 @@ export default (client: Client, statcord: Statcord.Client): void => { const staffRole = guild?.roles.cache.get(config.discord.staffRole) as Role // Log config info - log.debug(`Set guild to ${guild?.name} (${guild?.id})`) - log.debug(`Set log channel to #${logChannel.name} (${logChannel.id})`) - log.debug(`Set staff role to @${staffRole.name} (${staffRole.id})`) - log.debug(`Set shard count to ${config.discord.shardCount}`) + debug(`Set guild to ${guild?.name} (${guild?.id})`) + debug(`Set log channel to #${logChannel.name} (${logChannel.id})`) + debug(`Set staff role to @${staffRole.name} (${staffRole.id})`) - const statusText = "summer do the dev shuffle" + const statusText = "the suffering of humanity" client.user.setActivity(statusText, { type: ActivityType.Watching }) - log.debug(`Set custom status to ${statusText}`) + debug(`Set custom status to ${statusText}`, { sendWebhook:true }) const logEmbed1 = new EmbedBuilder() .setTitle("Status Log") @@ -78,8 +76,8 @@ export default (client: Client, statcord: Statcord.Client): void => { content: "Checking API connection.. OK", }, }) - } catch (e) { - log.error(e) + } catch (e:any) { + error(`\`${e}\``, { sendWebhook:true }) } mongoose @@ -87,17 +85,17 @@ export default (client: Client, statcord: Statcord.Client): void => { keepAlive: true, }) .then(() => { - log.info("Connected to MongoDB database...") + log("Connected to MongoDB database...") }) .catch((e) => { - log.error(`DB Error: ${e}`) + error(`DB Error: ${e}`) }) try { - log.debug("Linking commands...") + debug("Linking commands...") // linkCommandsOld(client); } catch (e) { - log.error("Error linking commands, exiting...") + error("Error linking commands, exiting...") process.abort() } }) diff --git a/src/scripts/DiscordJS/clearCommands.ts b/src/scripts/DiscordJS/clearCommands.ts index 6cc8e1e..ece469d 100644 --- a/src/scripts/DiscordJS/clearCommands.ts +++ b/src/scripts/DiscordJS/clearCommands.ts @@ -5,14 +5,13 @@ import {createSimpleLogger} from "simple-node-logger"; import {QuickDB} from "quick.db"; const rest = new REST({ version: '10' }).setToken(config.discord.token); -const log = createSimpleLogger("./data/mcb.log"); -log.setLevel('debug'); +import { debug,error,log } from '../../lib/tsabLogger'; const db = new QuickDB(); const sysInternals = db.table("sysInt"); -log.info('Starting deletion...') +log('Starting deletion...') const commands: never[] = [] rest.put(Routes.applicationGuildCommands(config.discord.clientId, config.discord.serverId), {body: commands}) - .then((data:any) => log.debug(`Successfully deleted all commands.`)) - .catch(log.error) \ No newline at end of file + .then((data:any) => debug(`Successfully deleted all commands.`)) + .catch(error) \ No newline at end of file diff --git a/src/scripts/DiscordJS/manCommandLoad.ts b/src/scripts/DiscordJS/manCommandLoad.ts index d065308..d97a50c 100644 --- a/src/scripts/DiscordJS/manCommandLoad.ts +++ b/src/scripts/DiscordJS/manCommandLoad.ts @@ -5,16 +5,15 @@ import {createSimpleLogger} from "simple-node-logger"; import {QuickDB} from "quick.db"; const rest = new REST({ version: '10' }).setToken(config.discord.token); -const log = createSimpleLogger("./data/mcb.log"); -log.setLevel('debug'); +import { debug,log,error } from '../../lib/tsabLogger'; const db = new QuickDB(); const sysInternals = db.table("sysInt"); -log.info('Manually syncing selected commands...') +log('Manually syncing selected commands...') const commands = [ new SlashCommandBuilder().setName('ping').setDescription("Replies with system latency"), ].map(command=>command.toJSON()); rest.put(Routes.applicationGuildCommands(config.discord.clientId, config.discord.serverId), {body: commands}) - .then((data:any) => log.debug(`Successfully registered ${data.length} application commands.`)) - .catch(log.error) \ No newline at end of file + .then((data:any) => debug(`Successfully registered ${data.length} application commands.`)) + .catch(error) \ No newline at end of file diff --git a/src/scripts/DiscordJS/syncCommands.ts b/src/scripts/DiscordJS/syncCommands.ts index e381ab5..fdf78d2 100644 --- a/src/scripts/DiscordJS/syncCommands.ts +++ b/src/scripts/DiscordJS/syncCommands.ts @@ -6,8 +6,7 @@ import {QuickDB} from "quick.db"; import fs from "fs"; const rest = new REST({ version: '10' }).setToken(config.discord.token); -const log = createSimpleLogger("./data/mcb.log"); -log.setLevel('debug'); +import { debug,log,error } from '../../lib/tsabLogger'; const db = new QuickDB(); const sysInternals = db.table("sysInt"); @@ -26,13 +25,13 @@ fs.readdirSync(commandDir).forEach(file => { if (cmd.data) { commands.push(cmd.data.toJSON()); console.log(cmd) - log.info(`Imported Slash Command: ${file}`); + log(`Imported Slash Command: ${file}`); } }) console.log('Syncing commands..') rest.put(Routes.applicationGuildCommands(config.discord.clientId, config.discord.serverId), {body: commands}) - .then((data:any) => log.debug(`Successfully registered ${data.length} application commands.`)) - .catch(log.error) + .then((data:any) => debug(`Successfully registered ${data.length} application commands.`)) + .catch(error) diff --git a/src/theHeart.ts b/src/theHeart.ts index 765eff0..fe45650 100644 --- a/src/theHeart.ts +++ b/src/theHeart.ts @@ -6,8 +6,7 @@ import * as figlet from "figlet"; import Statcord from "statcord.js"; import tempListener from "./listeners/customListeners/temp.listener"; import newCommandHandler from "./listeners/newCommandHandler"; - -const log = createSimpleLogger("./data/mcb.log"); +import { debug,log,warn,error } from './lib/tsabLogger' figlet.text( "TSAB Framework", @@ -19,7 +18,7 @@ figlet.text( }, function (err, data) { if (err) { - log.warn("Something went wrong..."); + warn("Something went wrong..."); console.dir(err); return; } @@ -27,8 +26,8 @@ figlet.text( } ); -log.info("Built and Maintained by SDS | Please wait for all services to start..."); -log.info("Starting bot..."); +log("Built and Maintained by SDS | Please wait for all services to start..."); +log("Starting bot..."); const client = new Client({ @@ -60,17 +59,17 @@ tempListener(client) try { client.login(config.discord.token).then(r => { - log.debug('Discord websocket connected!') + debug('Discord websocket connected!') }); } catch (e) { - log.warn('Error when connecting to Discord Gateway') + warn('Error when connecting to Discord Gateway', { sendWebhook: true }) } statcord.on("post", (status: any) => { if (!status) { - log.debug("Successful post"); + debug("Successful post"); } else { - log.warn(status) + warn(status, { sendWebhook:true }) }; }); diff --git a/src/utilities.ts b/src/utilities.ts index 0713b87..caff55d 100644 --- a/src/utilities.ts +++ b/src/utilities.ts @@ -2,8 +2,7 @@ import { config } from "../data/config" import { createSimpleLogger } from "simple-node-logger" import { QuickDB } from "quick.db" import { EmbedBuilder, WebhookClient } from "discord.js" - -const log = createSimpleLogger("./data/mcb.log") +import { debug,log,warn,error } from "./lib/tsabLogger" const db = new QuickDB() /** @@ -11,16 +10,16 @@ const db = new QuickDB() */ export function checkForInfo() { if (!config.discord.serverId) { - log.error("No server specified, exit to prevent further errors...") + error("No server specified, exit to prevent further errors...") return process.exit() } else if (!config.discord.logChannel) { - log.error("No log channel, exit to prevent further errors...") + error("No log channel, exit to prevent further errors...") return process.exit() } else if (!config.discord.staffRole) { - log.error("No staff role, exit to prevent further errors...") + error("No staff role, exit to prevent further errors...") return process.exit() } else { - return log.debug("All checks passed, starting bot..") + return debug("All checks passed, starting bot..") } } @@ -47,18 +46,18 @@ export async function disclaimerCheck(db: QuickDB, table: any) { (await table.get("registered")) === null || (await table.get("registered")) === false ) { - log.info("-----") - log.warn( + log("-----") + warn( "DISCLAIMER: SDS do not take responsibility for any loopholes or exploits in commands or internal systems." ) - log.warn( + warn( "Any known vulnerabilities in the code we ship will be fixed ASAP, but any code you create, modify and/or delete, is your responsibility." ) - log.warn( + warn( "This bot is NOT made to serve multiple guilds, it's only designed to serve 1 guild, so if you use the bot in multiple, things will at some point break." ) - log.info("-----") - log.debug("Disclaimer displayed, registering bot in DB") + log("-----") + debug("Disclaimer displayed, registering bot in DB") await table.set("registered", true) } @@ -88,12 +87,12 @@ export async function customLogger(mode: string, user: string) { /** * Report different logs to a designated Discord webhook - * @param {string} mode - What type of log will be sent. debug, info, warn, error, note + * @param {string} mode - What type of log will be sent. debug, log, warn, error, note * @param {string} text - Text to be sent along with the embed. * @return {object} webhook - Returns a DiscordJS Webhook object */ export async function webhookReporter(mode: string, text: string) { if (!config.tsabLoggerSetting.loggingWebhook) { - return log.error("No webhook found! Check your config!") + return error("No webhook found! Check your config!") } const whClient = new WebhookClient({ @@ -152,6 +151,6 @@ export async function webhookReporter(mode: string, text: string) { return await whClient.send({ embeds: [noteEmbed] }) default: - return log.warn("Not a correct log type!") + return warn("Not a valid log type!") } }