Skip to content

Update logger #264

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@
"prefer-const": ["warn", { "destructuring": "all" }],
"no-constant-condition": ["error", { "checkLoops": false }],
"import/extensions": ["warn", "always", { "ts": "never" }],
"no-throw-literal": "error"
"no-throw-literal": "error",
}
}
2 changes: 1 addition & 1 deletion API/stats/bestiary.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ function getBestiary(userProfile) {
maxMilestone: totalTiers / 10
};
} catch (error) {
console.log(error);
console.error(error);
return null;
}
}
Expand Down
2 changes: 1 addition & 1 deletion API/stats/chocolateFactory.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ module.exports = (profile) => {
level: profile.events?.easter?.chocolate_level || 0
};
} catch (error) {
console.log(error);
console.error(error);
return null;
}
};
3 changes: 1 addition & 2 deletions API/stats/crimson.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// CREDITS: by @Kathund (https://github.com/Kathund)

const { titleCase } = require("../constants/functions.js");

module.exports = (profile) => {
Expand Down Expand Up @@ -62,7 +61,7 @@ module.exports = (profile) => {
trophyFishing: getTrophyFish(profile)
};
} catch (error) {
console.log(error);
console.error(error);
return null;
}
};
Expand Down
2 changes: 1 addition & 1 deletion API/stats/dungeons.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ module.exports = (profile) => {
}
};
} catch (error) {
console.log(error);
console.error(error);
return null;
}
};
Expand Down
4 changes: 2 additions & 2 deletions API/stats/hotm.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ module.exports = (profile) => {
forgeItem.timeFinishedText =
timeFinished < Date.now() ? "Finished" : `ending ${moment(timeFinished).fromNow()}`;
} else {
console.log(item);
console.error(item);
forgeItem.name = "Unknown Item";
forgeItem.id = `UNKNOWN-${item.id}`;
}
Expand Down Expand Up @@ -66,7 +66,7 @@ module.exports = (profile) => {
forge: forgeItems
};
} catch (error) {
console.log(error);
console.error(error);
return null;
}
};
2 changes: 1 addition & 1 deletion API/stats/talismans.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ module.exports = async (profile) => {
return null;
}
} catch (error) {
console.log(error);
console.error(error);
return null;
}
};
Expand Down
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
process.on("uncaughtException", (error) => console.log(error));
const app = require("./src/Application.js");

Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
"scripts": {
"start": "node index.js",
"test": "jest --detectOpenHandles --forceExit",
"lint": "npx eslint .",
"lint:fix": "npx eslint . --fix",
"prettier": "npx prettier --check .",
"prettier:fix": "npx prettier --write .",
"lint": "npx eslint src/",
"lint:fix": "npx eslint src/ --fix",
"prettier": "npx prettier src/ --check",
"prettier:fix": "npx prettier src/ --write",
"nodemon": "nodemon index"
},
"repository": {
Expand Down
1 change: 1 addition & 0 deletions src/Application.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class Application {
constructor() {
require("./Configuration.js");
require("./Updater.js");
require("./Logger.js");
if (!existsSync("./data/")) mkdirSync("./data/", { recursive: true });
if (!existsSync("./data/linked.json")) writeFileSync("./data/linked.json", JSON.stringify({}));
}
Expand Down
22 changes: 12 additions & 10 deletions src/Logger.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable no-console */
const customLevels = { discord: 0, minecraft: 1, web: 2, warn: 3, error: 4, broadcast: 5, max: 6 };
const { createLogger, format, transports } = require("winston");
const config = require("../config.json");
const chalk = require("chalk");

const discordTransport = new transports.File({ level: "discord", filename: "./logs/discord.log" });
const minecraftTransport = new transports.File({ level: "minecraft", filename: "./logs/minecraft.log" });
const webTransport = new transports.File({ level: "web", filename: "./logs/web.log" });
Expand Down Expand Up @@ -115,12 +115,13 @@ function warnMessage(message) {
return console.log(chalk.bgYellow.black(`[${getCurrentTime()}] Warning >`) + " " + chalk.yellow(message));
}

function errorMessage(message) {
function errorMessage(error) {
const errorString = `${error.toString()}${error.stack?.replace(error.toString(), "")}`;
if (config.other.logToFiles) {
errorLogger.log("error", message);
errorLogger.log("error", errorString);
}

return console.log(chalk.bgRedBright.black(`[${getCurrentTime()}] Error >`) + " " + chalk.redBright(message));
return console.log(chalk.bgRedBright.black(`[${getCurrentTime()}] Error >`) + " " + chalk.redBright(errorString));
}

function broadcastMessage(message, location) {
Expand Down Expand Up @@ -174,13 +175,14 @@ async function updateMessage() {
console.log(chalk.bgRed.black(" ".repeat(columns).repeat(3)));
}

console.discord = discordMessage;
console.minecraft = minecraftMessage;
console.web = webMessage;
console.warn = warnMessage;
console.error = errorMessage;
console.broadcast = broadcastMessage;

module.exports = {
discordMessage,
minecraftMessage,
webMessage,
warnMessage,
errorMessage,
broadcastMessage,
getCurrentTime,
configUpdateMessage,
updateMessage
Expand Down
2 changes: 1 addition & 1 deletion src/Updater.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function updateCode() {

exec("git pull", (error, stdout, stderr) => {
if (error) {
console.error(`Git pull error: ${error}`);
console.error(error);
return;
}

Expand Down
6 changes: 3 additions & 3 deletions src/contracts/API/mowojangAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async function getUUID(username) {
} catch (error) {
// eslint-disable-next-line no-throw-literal
if (error.response.data === "Not found") throw "Invalid username.";
console.log(error);
console.error(error);
throw error;
}
}
Expand Down Expand Up @@ -57,7 +57,7 @@ async function getUsername(uuid) {

return data.name;
} catch (error) {
console.log(error);
console.error(error);
// eslint-disable-next-line no-throw-literal
if (error.response?.data === "Not found") throw "Invalid UUID.";
throw error;
Expand All @@ -75,7 +75,7 @@ async function resolveUsernameOrUUID(username) {
} catch (error) {
// eslint-disable-next-line no-throw-literal
if (error.response.data === "Not found") throw "Invalid Username Or UUID.";
console.log(error);
console.error(error);
throw error;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/discord/CommandHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class CommandHandler {

rest
.put(Routes.applicationGuildCommands(clientID, config.discord.bot.serverID), { body: commands })
.catch(console.error);
.catch((e) => console.error(e));
}
}

Expand Down
13 changes: 6 additions & 7 deletions src/discord/DiscordManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const MessageHandler = require("./handlers/MessageHandler.js");
const StateHandler = require("./handlers/StateHandler.js");
const CommandHandler = require("./CommandHandler.js");
const config = require("../../config.json");
const Logger = require(".././Logger.js");
const fs = require("fs");

class DiscordManager extends CommunicationBridge {
Expand Down Expand Up @@ -37,7 +36,7 @@ class DiscordManager extends CommunicationBridge {
this.client.on("messageCreate", (message) => this.messageHandler.onMessage(message));

this.client.login(config.discord.bot.token).catch((error) => {
Logger.errorMessage(error);
console.error(error);
});

client.commands = new Collection();
Expand Down Expand Up @@ -94,7 +93,7 @@ class DiscordManager extends CommunicationBridge {
const mode = chat === "debugChannel" ? "minecraft" : config.discord.other.messageMode.toLowerCase();
message = chat === "debugChannel" ? fullMessage : message;
if (message !== undefined && chat !== "debugChannel") {
Logger.broadcastMessage(
console.broadcast(
`${username} [${guildRank.replace(/§[0-9a-fk-or]/g, "").replace(/^\[|\]$/g, "")}]: ${message}`,
`Discord`
);
Expand All @@ -107,7 +106,7 @@ class DiscordManager extends CommunicationBridge {

const channel = await this.stateHandler.getChannel(chat || "Guild");
if (channel === undefined) {
Logger.errorMessage(`Channel ${chat} not found!`);
console.error(`Channel ${chat} not found!`);
return;
}
if (username === bot.username && message.endsWith("Check Discord Bridge for image.")) {
Expand Down Expand Up @@ -182,7 +181,7 @@ class DiscordManager extends CommunicationBridge {
}

async onBroadcastCleanEmbed({ message, color, channel }) {
Logger.broadcastMessage(message, "Event");
console.broadcast(message, "Event");

channel = await this.stateHandler.getChannel(channel);
channel.send({
Expand All @@ -196,7 +195,7 @@ class DiscordManager extends CommunicationBridge {
}

async onBroadcastHeadedEmbed({ message, title, icon, color, channel }) {
Logger.broadcastMessage(message, "Event");
console.broadcast(message, "Event");

channel = await this.stateHandler.getChannel(channel);
channel.send({
Expand All @@ -214,7 +213,7 @@ class DiscordManager extends CommunicationBridge {
}

async onPlayerToggle({ fullMessage, username, message, color, channel }) {
Logger.broadcastMessage(message, "Event");
console.broadcast(message, "Event");
channel = await this.stateHandler.getChannel(channel);
switch (config.discord.other.messageMode.toLowerCase()) {
case "bot":
Expand Down
2 changes: 1 addition & 1 deletion src/discord/commands/helpCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ module.exports = {
await interaction.followUp({ embeds: [embed] });
}
} catch (error) {
console.log(error);
console.error(error);
}
}
};
2 changes: 1 addition & 1 deletion src/discord/commands/infoCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ module.exports = {
);
await interaction.followUp({ embeds: [infoEmbed] });
} catch (e) {
console.log(e);
console.error(e);
}
}
};
2 changes: 1 addition & 1 deletion src/discord/commands/verifyCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ module.exports = {

await updateRolesCommand.execute(interaction, user);
} catch (error) {
console.log(error);
console.error(error);
// eslint-disable-next-line no-ex-assign
error = error
.toString()
Expand Down
6 changes: 2 additions & 4 deletions src/discord/events/interactionCreate.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const { ErrorEmbed, SuccessEmbed } = require("../../contracts/embedHandler.js");
// eslint-disable-next-line no-unused-vars
const { CommandInteraction } = require("discord.js");
const config = require("../../../config.json");
const Logger = require("../.././Logger.js");

module.exports = {
name: "interactionCreate",
Expand All @@ -24,7 +23,7 @@ module.exports = {
return;
}

Logger.discordMessage(`${interaction.user.username} - [${interaction.commandName}]`);
console.discord(`${interaction.user.username} - [${interaction.commandName}]`);

if (command.verificationCommand === true && config.verification.enabled === false) {
throw new HypixelDiscordChatBridgeError("Verification is disabled.");
Expand Down Expand Up @@ -54,8 +53,7 @@ module.exports = {
await interaction.followUp({ embeds: [embed] });
}
} catch (error) {
console.log(error);

console.error(error);
const errrorMessage =
error instanceof HypixelDiscordChatBridgeError
? ""
Expand Down
4 changes: 2 additions & 2 deletions src/discord/handlers/MessageHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class MessageHandler {

this.discord.broadcastMessage(messageData);
} catch (error) {
console.log(error);
console.error(error);
}
}

Expand Down Expand Up @@ -111,7 +111,7 @@ class MessageHandler {

return mentionedUserName ?? null;
} catch (error) {
console.log(error);
console.error(error);
return null;
}
}
Expand Down
11 changes: 5 additions & 6 deletions src/discord/handlers/StateHandler.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
const config = require("../../../config.json");
const Logger = require("../../Logger.js");

class StateHandler {
constructor(discord) {
this.discord = discord;
}

async onReady() {
Logger.discordMessage("Client ready, logged in as " + this.discord.client.user.tag);
console.discord("Client ready, logged in as " + this.discord.client.user.tag);
this.discord.client.user.setPresence({
activities: [{ name: `/help | by @duckysolucky` }]
});

global.guild = await client.guilds.fetch(config.discord.bot.serverID);
Logger.discordMessage("Guild ready, successfully fetched " + guild.name);
console.discord(`Guild ready, successfully fetched ${guild.name}`);

const channel = await this.getChannel("Guild");
if (channel === undefined) {
return Logger.errorMessage(`Channel "Guild" not found!`);
return console.error(`Channel "Guild" not found!`);
}

if (config.verification.autoUpdater) require("../other/updateUsers.js");
Expand All @@ -36,7 +35,7 @@ class StateHandler {
async onClose() {
const channel = await this.getChannel("Guild");
if (channel === undefined) {
return Logger.errorMessage(`Channel "Guild" not found!`);
return console.error(`Channel "Guild" not found!`);
}

await channel.send({
Expand All @@ -51,7 +50,7 @@ class StateHandler {

async getChannel(type) {
if (typeof type !== "string" || type === undefined) {
return Logger.errorMessage(`Channel type must be a string!`);
return console.error(`Channel type must be a string!`);
}

switch (type.replace(/§[0-9a-fk-or]/g, "").trim()) {
Expand Down
9 changes: 4 additions & 5 deletions src/discord/other/updateUsers.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
const updateRolesCommand = require("../commands/forceUpdateEveryone.js");
const config = require("../../../config.json");
const Logger = require("../../Logger.js");
const cron = require("node-cron");

if (config.verification.autoUpdater) {
Logger.discordMessage(`RoleSync ready, executing every ${config.verification.autoUpdaterInterval} hours.`);
console.discord(`RoleSync ready, executing every ${config.verification.autoUpdaterInterval} hours.`);
cron.schedule(`0 */${config.verification.autoUpdaterInterval} * * *`, async () => {
try {
Logger.discordMessage("Executing RoleSync...");
console.discord("Executing RoleSync...");
await updateRolesCommand.execute(null, true);
Logger.discordMessage("RoleSync successfully executed.");
console.discord("RoleSync successfully executed.");
} catch (error) {
console.log(error);
console.error(error);
}
});
}
Loading
Loading