Add logger to project (#183)
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

# Description

Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.

- Add the winston package to handle logging
- Add logging to the project's logic

#146

## Type of change

Please delete options that are not relevant.

- [x] New feature (non-breaking change which adds functionality)

# How Has This Been Tested?

Please describe the tests that you ran to verify the changes. Provide instructions so we can reproduce. Please also list any relevant details to your test configuration.

# Checklist

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that provde my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream modules

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/183
Reviewed-by: VylpesTester <tester@vylpes.com>
Co-authored-by: Ethan Lane <ethan@vylpes.com>
Co-committed-by: Ethan Lane <ethan@vylpes.com>
This commit is contained in:
Ethan Lane 2024-03-15 17:33:12 +00:00 committed by Vylpes
parent 42dfe2d047
commit 5dd50a3f3b
27 changed files with 465 additions and 26 deletions

65
src/client/appLogger.ts Normal file
View file

@ -0,0 +1,65 @@
import { Logger, createLogger, format, transports } from "winston";
export default class AppLogger {
public static Logger: Logger;
public static InitialiseLogger(logLevel: string, outputToConsole: boolean) {
const customFormat = format.printf(({ level, message, timestamp, label }) => {
return `${timestamp} [${label}] ${level}: ${message}`;
});
const logger = createLogger({
level: logLevel,
format: format.combine(
format.timestamp({
format: "YYYY-MM-DD HH:mm:ss"
}),
format.errors({ stack: true }),
format.splat(),
customFormat,
),
defaultMeta: { service: "bot" },
transports: [
new transports.File({ filename: "error.log", level: "error" }),
new transports.File({ filename: "combined.log" }),
],
});
if (outputToConsole) {
logger.add(new transports.Console({
format: format.combine(
format.colorize(),
format.timestamp(),
customFormat,
)}));
}
AppLogger.Logger = logger;
AppLogger.LogInfo("AppLogger", `Log Level: ${logLevel}`);
}
public static LogError(label: string, message: string) {
AppLogger.Logger.error({ label, message });
}
public static LogWarn(label: string, message: string) {
AppLogger.Logger.warn({ label, message });
}
public static LogInfo(label: string, message: string) {
AppLogger.Logger.info({ label, message });
}
public static LogVerbose(label: string, message: string) {
AppLogger.Logger.verbose({ label, message });
}
public static LogDebug(label: string, message: string) {
AppLogger.Logger.debug({ label, message });
}
public static LogSilly(label: string, message: string) {
AppLogger.Logger.silly({ label, message });
}
}

View file

@ -13,6 +13,7 @@ import { Environment } from "../constants/Environment";
import Webhooks from "../webhooks";
import CardMetadataFunction from "../Functions/CardMetadataFunction";
import { SeriesMetadata } from "../contracts/SeriesMetadata";
import AppLogger from "./appLogger";
export class CoreClient extends Client {
private static _commandItems: ICommandItem[];
@ -44,6 +45,14 @@ export class CoreClient extends Client {
super({ intents: intents });
dotenv.config();
CoreClient.Environment = Number(process.env.BOT_ENV);
const loglevel = process.env.BOT_LOGLEVEL ?? "info";
AppLogger.InitialiseLogger(loglevel, CoreClient.Environment == Environment.Local);
AppLogger.LogInfo("Client", "Initialising Client");
CoreClient._commandItems = [];
CoreClient._buttonEvents = [];
@ -51,21 +60,24 @@ export class CoreClient extends Client {
this._util = new Util();
this._webhooks = new Webhooks();
CoreClient.Environment = Number(process.env.BOT_ENV);
console.log(`Bot Environment: ${CoreClient.Environment}`);
AppLogger.LogInfo("Client", `Environment: ${CoreClient.Environment}`);
CoreClient.AllowDrops = true;
}
public async start() {
if (!process.env.BOT_TOKEN) {
console.error("BOT_TOKEN is not defined in .env");
AppLogger.LogError("Client", "BOT_TOKEN is not defined in .env");
return;
}
await AppDataSource.initialize()
.then(() => console.log("App Data Source Initialised"))
.catch(err => console.error("Error initialising App Data Source", err));
.then(() => AppLogger.LogInfo("Client", "App Data Source Initialised"))
.catch(err => {
AppLogger.LogError("Client", "App Data Source Initialisation Failed");
AppLogger.LogError("Client", err);
throw err;
});
super.on("interactionCreate", this._events.onInteractionCreate);
super.on("ready", this._events.onReady);
@ -90,6 +102,8 @@ export class CoreClient extends Client {
if ((environment & CoreClient.Environment) == CoreClient.Environment) {
CoreClient._commandItems.push(item);
AppLogger.LogVerbose("Client", `Registered Command: ${name}`);
}
}
@ -112,6 +126,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Channel Create Event");
}
public static RegisterChannelDeleteEvent(fn: (channel: DMChannel | NonThreadGuildBasedChannel) => void) {
@ -133,6 +149,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Channel Delete Event");
}
public static RegisterChannelUpdateEvent(fn: (channel: DMChannel | NonThreadGuildBasedChannel) => void) {
@ -154,6 +172,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Channel Update Event");
}
public static RegisterGuildBanAddEvent(fn: (ban: GuildBan) => void) {
@ -175,6 +195,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Guild Ban Add Event");
}
public static RegisterGuildBanRemoveEvent(fn: (channel: GuildBan) => void) {
@ -196,6 +218,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Guild Ban Remove Event");
}
public static RegisterGuildCreateEvent(fn: (guild: Guild) => void) {
@ -217,6 +241,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Guild Create Event");
}
public static RegisterGuildMemberAddEvent(fn: (member: GuildMember) => void) {
@ -238,6 +264,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Guild Member Add Event");
}
public static RegisterGuildMemberRemoveEvent(fn: (member: GuildMember | PartialGuildMember) => void) {
@ -259,6 +287,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Guild Member Remove Event");
}
public static GuildMemebrUpdate(fn: (oldMember: GuildMember | PartialGuildMember, newMember: GuildMember) => void) {
@ -280,6 +310,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Guild Member Update Event");
}
public static RegisterMessageCreateEvent(fn: (message: Message<boolean>) => void) {
@ -301,6 +333,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Message Create Event");
}
public static RegisterMessageDeleteEvent(fn: (message: Message<boolean> | PartialMessage) => void) {
@ -322,6 +356,8 @@ export class CoreClient extends Client {
MessageUpdate: [],
};
}
AppLogger.LogVerbose("Client", "Registered Message Delete Event");
}
public static RegisterMessageUpdateEvent(fn: (oldMessage: Message<boolean> | PartialMessage, newMessage: Message<boolean> | PartialMessage) => void) {
@ -343,6 +379,8 @@ export class CoreClient extends Client {
MessageUpdate: [ fn ],
};
}
AppLogger.LogVerbose("Client", "Registered Message Update Event");
}
public static RegisterButtonEvent(buttonId: string, event: ButtonEvent, environment: Environment = Environment.All) {
@ -354,6 +392,8 @@ export class CoreClient extends Client {
if ((environment & CoreClient.Environment) == CoreClient.Environment) {
CoreClient._buttonEvents.push(item);
AppLogger.LogVerbose("Client", `Registered Button Event: ${buttonId}`);
}
}
}

View file

@ -1,22 +1,25 @@
import { Interaction } from "discord.js";
import ChatInputCommand from "./interactionCreate/ChatInputCommand";
import Button from "./interactionCreate/Button";
import AppLogger from "./appLogger";
export class Events {
public async onInteractionCreate(interaction: Interaction) {
if (!interaction.guildId) return;
if (interaction.isChatInputCommand()) {
AppLogger.LogVerbose("Client", `ChatInputCommand: ${interaction.commandName}`);
ChatInputCommand.onChatInput(interaction);
}
if (interaction.isButton()) {
AppLogger.LogVerbose("Client", `Button: ${interaction.customId}`);
Button.onButtonClicked(interaction);
}
}
// Emit when bot is logged in and ready to use
public onReady() {
console.log("Ready");
AppLogger.LogInfo("Client", "Ready");
}
}

View file

@ -1,5 +1,6 @@
import { ButtonInteraction } from "discord.js";
import { CoreClient } from "../client";
import AppLogger from "../appLogger";
export default class Button {
public static async onButtonClicked(interaction: ButtonInteraction) {
@ -8,14 +9,19 @@ export default class Button {
const item = CoreClient.buttonEvents.find(x => x.ButtonId == interaction.customId.split(" ")[0]);
if (!item) {
AppLogger.LogVerbose("Button", `Event not found: ${interaction.customId}`);
await interaction.reply("Event not found");
return;
}
try {
AppLogger.LogDebug("Button", `Executing ${interaction.customId}`);
item.Event.execute(interaction);
} catch (e) {
console.error(e);
AppLogger.LogError("Button", `Error occurred while executing event: ${interaction.customId}`);
AppLogger.LogError("Button", e as string);
await interaction.reply("An error occurred while executing the event");
}

View file

@ -1,6 +1,7 @@
import { Interaction } from "discord.js";
import { CoreClient } from "../client";
import ICommandItem from "../../contracts/ICommandItem";
import AppLogger from "../appLogger";
export default class ChatInputCommand {
public static async onChatInput(interaction: Interaction) {
@ -13,6 +14,8 @@ export default class ChatInputCommand {
if (!itemForServer) {
if (!item) {
AppLogger.LogVerbose("ChatInputCommand", `Command not found: ${interaction.commandName}`);
await interaction.reply("Command not found");
return;
}
@ -23,9 +26,12 @@ export default class ChatInputCommand {
}
try {
AppLogger.LogDebug("Command", `Executing ${interaction.commandName}`);
itemToUse.Command.execute(interaction);
} catch (e) {
console.error(e);
AppLogger.LogError("ChatInputCommand", `Error occurred while executing command: ${interaction.commandName}`);
AppLogger.LogError("ChatInputCommand", e as string);
await interaction.reply("An error occurred while executing the command");
}

View file

@ -1,6 +1,7 @@
import { Client, REST, Routes, SlashCommandBuilder } from "discord.js";
import EventExecutors from "../contracts/EventExecutors";
import { CoreClient } from "./client";
import AppLogger from "./appLogger";
export class Util {
public loadSlashCommands(client: Client) {
@ -29,6 +30,8 @@ export class Util {
const rest = new REST({ version: "10" }).setToken(process.env.BOT_TOKEN!);
AppLogger.LogVerbose("Util", `REST PUT: ${globalCommandData.flatMap(x => x.name).join(", ")}`);
rest.put(
Routes.applicationCommands(process.env.BOT_CLIENTID!),
{
@ -49,6 +52,8 @@ export class Util {
if (!client.guilds.cache.has(guild)) continue;
AppLogger.LogVerbose("Util", `REST PUT: ${guild} - ${guildCommandData.flatMap(x => x.name).join(", ")}`);
rest.put(
Routes.applicationGuildCommands(process.env.BOT_CLIENTID!, guild),
{