Skip to content

feat: add logger #82

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

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# SETUP
DISCORD_TOKEN=
LOGLEVEL=

# DB
REDIS_URL=
Expand Down
4 changes: 4 additions & 0 deletions .eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ settings:
import/resolver:

rules:
no-restricted-syntax:
- error
- selector: CallExpression[callee.object.name='console'][callee.property.name!=/^(log|warn|error|info|trace)$/]
message: Use logger instead of console
import/exports-last: error
import/first: error
import/no-duplicates: error
Expand Down
3 changes: 3 additions & 0 deletions src/core/createModule.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { constantCase } from 'change-case';
import type { ClientEvents, ClientOptions } from 'discord.js';
import type { Logger } from 'pino';
import type { ZodTypeAny } from 'zod';
import { z } from 'zod';

Expand All @@ -11,6 +12,7 @@ type InferredZodShape<Shape extends Record<string, ZodTypeAny>> = {

interface Context<Env extends Record<string, ZodTypeAny>> {
env: InferredZodShape<Env>;
logger: Logger;
}

type ModuleFunction<Env extends Record<string, ZodTypeAny>, ReturnType> = (
Expand All @@ -31,6 +33,7 @@ type BotModule<Env extends Record<string, ZodTypeAny>> = {

interface CreatedModuleInput {
env: unknown;
logger: Logger;
}

type ModuleFactory = (input: CreatedModuleInput) => Promise<CreatedModule>;
Expand Down
2 changes: 2 additions & 0 deletions src/core/loadModules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { checkUniqueSlashCommandNames } from './checkUniqueSlashCommandNames';
import type { CreatedModule } from './createModule';
import { env } from './env';
import { pushCommands, routeCommands } from './loaderCommands';
import { coreLogger } from './logger';
import { routeHandlers } from './routeHandlers';

export const loadModules = async (
Expand All @@ -15,6 +16,7 @@ export const loadModules = async (
const botCommands = modules.flatMap((module) => module.slashCommands ?? []);

checkUniqueSlashCommandNames(botCommands);
coreLogger.info('Routing slashcommands to interactionCreate event.');
routeCommands(client, botCommands);

const clientId = client.application?.id;
Expand Down
2 changes: 2 additions & 0 deletions src/core/loaderCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {

import type { BotCommand } from '../types/bot';
import { deleteExistingCommands } from './deleteExistingCommands';
import { coreLogger } from './logger';

interface PushCommandsOptions {
commands: RESTPostAPIChatInputApplicationCommandsJSONBody[];
Expand Down Expand Up @@ -62,6 +63,7 @@ export const pushCommands = async ({
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: commands,
});
coreLogger.info('All commands are pushed.');
};

export const routeCommands = (client: Client<true>, botCommands: BotCommand[]) =>
Expand Down
18 changes: 18 additions & 0 deletions src/core/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import createLogger, { type LoggerOptions } from 'pino';

const developmentOptionsOverride: LoggerOptions = {
transport: {
target: './pinoTransportModule',
},
level: process.env['LOGLEVEL'] ?? 'debug',
};

const defaultLogger = createLogger({
level: process.env['LOGLEVEL'] ?? 'info',
...(process.env['NODE_ENV'] === 'production' ? {} : developmentOptionsOverride),
});

export const createLoggerForModule = (moduleName: string) =>
defaultLogger.child({ module: moduleName });

export const coreLogger = createLoggerForModule('core');
11 changes: 11 additions & 0 deletions src/core/pinoTransportModule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { red, white } from 'colorette';
import pretty from 'pino-pretty';

export default (opts: Parameters<typeof pretty>) =>
pretty({
...opts,
colorize: true,
messageFormat: white(`[${red('{module}')}] {msg}`),
hideObject: true,
ignore: 'pid,hostname',
});
1 change: 1 addition & 0 deletions src/core/routeHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Client, ClientEvents } from 'discord.js';

import type { EventHandler } from '../types/bot';
import type { CreatedModule } from './createModule';
import { coreLogger } from './logger';

const handleEvent = async (
eventHandlers: EventHandler[],
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@ if (!client.isReady()) {

await loadModules(client, createdModules);

console.log('Bot started.');
coreLogger.info('Bot fully started.');
3 changes: 1 addition & 2 deletions src/modules/recurringMessage/recurringMessage.helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ export const createRecurringMessage = (
() => {
const channel = client.channels.cache.get(channelId);
if (!channel || !channel.isTextBased()) {
console.error(`Channel ${channelId} not found`);
return;
throw new Error(`Channel ${channelId} not found`);
}
void channel.send(message);
},
Expand Down
16 changes: 15 additions & 1 deletion src/modules/voiceOnDemand/voiceOnDemand.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export const voiceOnDemand = createModule({
//NOTES: this is a potential race condition.
await cache.set('lobbyIds', [...lobbyIds, id]);

logger.info(`Created voice on demand voice channel ${id}`);
await interaction.reply({
content: 'Created voice on demand voice channel.',
ephemeral: true,
Expand All @@ -60,7 +61,7 @@ export const voiceOnDemand = createModule({
},
},
],
eventHandlers: () => ({
eventHandlers: ({ logger }) => ({
voiceStateUpdate: async (oldState, newState) => {
const lobbyIds = await cache.get('lobbyIds', []);
const onDemandChannels = await cache.get('onDemandChannels', []);
Expand All @@ -73,10 +74,18 @@ export const voiceOnDemand = createModule({
}

if (isOnDemandChannel && isLeaveState(oldState)) {
logger.debug(
{ guild: newState.guild.id },
`User ${oldState.member.displayName} left the on-demand channel`,
);
await handleLeaveOnDemand(oldState);
}

if (isLobbyChannel && isJoinState(newState)) {
logger.debug(
{ guild: newState.guild.id },
`User ${newState.member.displayName} joined the lobby`,
);
await handleJoinLobby(newState);
}
},
Expand All @@ -92,6 +101,11 @@ export const voiceOnDemand = createModule({
return;
}

logger.info(
{ guild: channel.guild.id },
`Voice on demand voice channel ${channel.id} was deleted`,
);

await cache.set(
'lobbyIds',
lobbyIds.filter((lobbyId) => lobbyId !== channel.id),
Expand Down
5 changes: 5 additions & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
//eslint-disable-next-line import/no-extraneous-dependencies
import { defineConfig } from 'tsup';

export default defineConfig({
clean: true,
entry: {
main: 'src/main.ts',
pinoTransportModule: 'src/core/pinoTransportModule.ts',
},
format: ['esm'],
keepNames: true,
minify: true,
Expand Down