From 7df5d14e282535c95f40f98daf53631394df06a7 Mon Sep 17 00:00:00 2001 From: JT2M0L3Y Date: Wed, 21 Oct 2026 20:08:11 -0700 Subject: [PATCH] stateful logging --- package.json | 5 +- src/commands/capacity.ts | 5 +- src/commands/cleanUserChannelHistory.ts | 4 +- src/commands/disable.ts | 5 +- src/commands/messageStream.ts | 5 +- src/commands/switchModel.ts | 4 +- src/commands/threadCreate.ts | 5 +- src/commands/threadPrivateCreate.ts | 5 +- src/events/interactionCreate.ts | 9 +- src/events/messageCreate.ts | 12 +-- src/events/ready.ts | 2 +- src/utils/commands.ts | 9 +- src/utils/handlers/chatHistoryHandler.ts | 10 +- src/utils/handlers/configHandler.ts | 6 +- tests/logger.test.ts | 19 ++++ tests/loggerIntegration.test.ts | 123 +++++++++++++++++++++++ 16 files changed, 187 insertions(+), 41 deletions(-) create mode 100644 tests/loggerIntegration.test.ts diff --git a/package.json b/package.json index 01ad3e3..2f788af 100644 --- a/package.json +++ b/package.json @@ -42,8 +42,5 @@ "engines": { "npm": ">=10.9.0", "node": ">=24.0.0" - }, - "allowScripts": { - "esbuild@0.25.12": true } -} +} \ No newline at end of file diff --git a/src/commands/capacity.ts b/src/commands/capacity.ts index 77504b3..8005942 100644 --- a/src/commands/capacity.ts +++ b/src/commands/capacity.ts @@ -1,5 +1,6 @@ import { Client, ChatInputCommandInteraction, ApplicationCommandOptionType, MessageFlags } from 'discord.js' import { openConfig, SlashCommand, UserCommand } from '../utils/index.js' +import type { Logger as PinoLogger } from 'pino' export const Capacity: SlashCommand = { name: 'modify-capacity', @@ -16,13 +17,13 @@ export const Capacity: SlashCommand = { ], // Query for message information and set the style - run: async (client: Client, interaction: ChatInputCommandInteraction) => { + run: async (client: Client, interaction: ChatInputCommandInteraction, logger: PinoLogger) => { // fetch channel and message const channel = await client.channels.fetch(interaction.channelId) if (!channel || !UserCommand.includes(channel.type)) return // set state of bot chat features - openConfig(`${interaction.user.username}-config.json`, interaction.commandName, + openConfig(logger, `${interaction.user.username}-config.json`, interaction.commandName, interaction.options.getNumber('context-capacity') ) diff --git a/src/commands/cleanUserChannelHistory.ts b/src/commands/cleanUserChannelHistory.ts index 0eb2c84..338ab25 100644 --- a/src/commands/cleanUserChannelHistory.ts +++ b/src/commands/cleanUserChannelHistory.ts @@ -1,12 +1,13 @@ import { Channel, Client, CommandInteraction, MessageFlags, TextChannel } from 'discord.js' import { clearChannelInfo, SlashCommand, UserCommand } from '../utils/index.js' +import type { Logger as PinoLogger } from 'pino' export const ClearUserChannelHistory: SlashCommand = { name: 'clear-user-channel-history', description: 'clears history for user in the current channel', // Clear channel history for intended user - run: async (client: Client, interaction: CommandInteraction) => { + run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => { // fetch current channel const channel: Channel | null = await client.channels.fetch(interaction.channelId) @@ -15,6 +16,7 @@ export const ClearUserChannelHistory: SlashCommand = { // clear channel info for user const successfulWipe = await clearChannelInfo( + logger, interaction.channelId, interaction.channel as TextChannel, interaction.user.username diff --git a/src/commands/disable.ts b/src/commands/disable.ts index c599de9..c0e4178 100644 --- a/src/commands/disable.ts +++ b/src/commands/disable.ts @@ -1,5 +1,6 @@ import { Client, ChatInputCommandInteraction, ApplicationCommandOptionType, MessageFlags } from 'discord.js' import { AdminCommand, openConfig, SlashCommand } from '../utils/index.js' +import type { Logger as PinoLogger } from 'pino' export const Disable: SlashCommand = { name: 'toggle-chat', @@ -16,7 +17,7 @@ export const Disable: SlashCommand = { ], // Query for message information and set the style - run: async (client: Client, interaction: ChatInputCommandInteraction) => { + run: async (client: Client, interaction: ChatInputCommandInteraction, logger: PinoLogger) => { // fetch channel and message const channel = await client.channels.fetch(interaction.channelId) if (!channel || !AdminCommand.includes(channel.type)) return @@ -31,7 +32,7 @@ export const Disable: SlashCommand = { } // set state of bot chat features - openConfig(`${interaction.guildId}-config.json`, interaction.commandName, + openConfig(logger, `${interaction.guildId}-config.json`, interaction.commandName, interaction.options.getBoolean('enabled') ) diff --git a/src/commands/messageStream.ts b/src/commands/messageStream.ts index b99081b..df225e9 100644 --- a/src/commands/messageStream.ts +++ b/src/commands/messageStream.ts @@ -1,5 +1,6 @@ import { ApplicationCommandOptionType, Client, ChatInputCommandInteraction, MessageFlags } from 'discord.js' import { openConfig, SlashCommand, UserCommand } from '../utils/index.js' +import type { Logger as PinoLogger } from 'pino' export const MessageStream: SlashCommand = { name: 'message-stream', @@ -16,13 +17,13 @@ export const MessageStream: SlashCommand = { ], // change preferences based on command - run: async (client: Client, interaction: ChatInputCommandInteraction) => { + run: async (client: Client, interaction: ChatInputCommandInteraction, logger: PinoLogger) => { // verify channel const channel = await client.channels.fetch(interaction.channelId) if (!channel || !UserCommand.includes(channel.type)) return // save value to json and write to it - openConfig(`${interaction.user.username}-config.json`, interaction.commandName, + openConfig(logger, `${interaction.user.username}-config.json`, interaction.commandName, interaction.options.getBoolean('stream') ) diff --git a/src/commands/switchModel.ts b/src/commands/switchModel.ts index 345a37d..1d78d60 100644 --- a/src/commands/switchModel.ts +++ b/src/commands/switchModel.ts @@ -36,7 +36,7 @@ export const SwitchModel: SlashCommand = { for (const model in response.models) { const currentModel: ModelResponse = response.models[model] if (currentModel.name.startsWith(modelInput)) { - openConfig(`${interaction.user.username}-config.json`, interaction.commandName, modelInput) + openConfig(logger, `${interaction.user.username}-config.json`, interaction.commandName, modelInput) // successful switch interaction.editReply({ @@ -52,7 +52,7 @@ export const SwitchModel: SlashCommand = { // todo: problem can be here if async messes up if (switchSuccess) { // set model now that it exists - openConfig(`${interaction.user.username}-config.json`, interaction.commandName, modelInput) + openConfig(logger, `${interaction.user.username}-config.json`, interaction.commandName, modelInput) return } diff --git a/src/commands/threadCreate.ts b/src/commands/threadCreate.ts index 1b9153b..8b922b9 100644 --- a/src/commands/threadCreate.ts +++ b/src/commands/threadCreate.ts @@ -1,12 +1,13 @@ import { ChannelType, Client, CommandInteraction, MessageFlags, TextChannel, ThreadChannel } from 'discord.js' import { AdminCommand, openChannelInfo, SlashCommand } from '../utils/index.js' +import type { Logger as PinoLogger } from 'pino' export const ThreadCreate: SlashCommand = { name: 'thread', description: 'creates a thread and mentions user', // Query for server information - run: async (client: Client, interaction: CommandInteraction) => { + run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => { // fetch the channel const channel = await client.channels.fetch(interaction.channelId) if (!channel || !AdminCommand.includes(channel.type)) return @@ -21,7 +22,7 @@ export const ThreadCreate: SlashCommand = { thread.send(`Hello ${interaction.user} and others! \n\nIt's nice to meet you. Please talk to me by typing **@${client.user?.username}** with your message.`) // handle storing this chat channel - openChannelInfo(thread.id, thread as ThreadChannel, interaction.user.tag) + openChannelInfo(logger, thread.id, thread as ThreadChannel, interaction.user.tag) // user only reply return interaction.reply({ diff --git a/src/commands/threadPrivateCreate.ts b/src/commands/threadPrivateCreate.ts index 578f2eb..f31fc26 100644 --- a/src/commands/threadPrivateCreate.ts +++ b/src/commands/threadPrivateCreate.ts @@ -1,12 +1,13 @@ import { ChannelType, Client, CommandInteraction, MessageFlags, TextChannel, ThreadChannel } from 'discord.js' import { AdminCommand, openChannelInfo, SlashCommand } from '../utils/index.js' +import type { Logger as PinoLogger } from 'pino' export const PrivateThreadCreate: SlashCommand = { name: 'private-thread', description: 'creates a private thread and mentions user', // Query for server information - run: async (client: Client, interaction: CommandInteraction) => { + run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => { // fetch the channel const channel = await client.channels.fetch(interaction.channelId) if (!channel || !AdminCommand.includes(channel.type)) return @@ -22,7 +23,7 @@ export const PrivateThreadCreate: SlashCommand = { // handle storing this chat channel // store: thread.id, thread.name - openChannelInfo(thread.id, thread as ThreadChannel, interaction.user.tag) + openChannelInfo(logger, thread.id, thread as ThreadChannel, interaction.user.tag) // user only reply return interaction.reply({ diff --git a/src/events/interactionCreate.ts b/src/events/interactionCreate.ts index 8ea3fb9..dad36ca 100644 --- a/src/events/interactionCreate.ts +++ b/src/events/interactionCreate.ts @@ -1,5 +1,6 @@ import { event, Events } from '../utils/index.js' import commands from '../commands/index.js' +import { createLogger } from '../components/index.js' /** * Interaction creation listener for the client @@ -15,5 +16,11 @@ export default event(Events.InteractionCreate, async ({ logger, client }, intera if (!command) return // the command exists, execute it - command.run(client, interaction, logger) + const commandLogger = createLogger({ + component: 'command', + command: command.name + }, logger) + + void Promise.resolve(command.run(client, interaction, commandLogger)) + .catch(error => commandLogger.error({ err: error }, 'Command execution failed')) }) \ No newline at end of file diff --git a/src/events/messageCreate.ts b/src/events/messageCreate.ts index d8e48cf..dae5053 100644 --- a/src/events/messageCreate.ts +++ b/src/events/messageCreate.ts @@ -33,7 +33,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist if (channelContextHistory.length === 0) { channelContextHistory = await new Promise((resolve) => { - addToChannelContext(message.channelId, + addToChannelContext(logger, message.channelId, message.channel as TextChannel ) getChannelInfo(`${message.channelId}-context.json`, (channelInfo) => { @@ -68,7 +68,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist }) // Store in Channel Context - addToChannelContext(message.channelId, + addToChannelContext(logger, message.channelId, message.channel as TextChannel, channelHistory.getItems() ) @@ -93,7 +93,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist // check if config.json exists if (config === undefined) { // Allowing chat options to be available - openConfig(`${message.guildId}-config.json`, 'toggle-chat', true) + openConfig(logger, `${message.guildId}-config.json`, 'toggle-chat', true) reject(new Error('Failed to locate or create Server Preferences\n\nPlease try chatting again...')) } @@ -125,7 +125,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist userConfig = await new Promise((resolve, reject) => { getUserConfig(`${message.author.username}-config.json`, (config) => { if (config === undefined) { - openConfig(`${message.author.username}-config.json`, 'switch-model', defaultModel) + openConfig(logger, `${message.author.username}-config.json`, 'switch-model', defaultModel) reject(new Error(`No User Preferences is set up.\n\nCreating new preferences file for ${message.author.username}\nPlease try chatting again.`)) return } @@ -175,7 +175,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist if (chatMessages.length === 0) { chatMessages = await new Promise((resolve, reject) => { - openChannelInfo(message.channelId, + openChannelInfo(logger, message.channelId, message.channel as TextChannel, message.author.tag ) @@ -225,7 +225,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist }) // only update the json on success - openChannelInfo(message.channelId, + openChannelInfo(logger, message.channelId, message.channel as TextChannel, message.author.tag, msgHist.getItems() diff --git a/src/events/ready.ts b/src/events/ready.ts index 96cb772..6cc3c46 100644 --- a/src/events/ready.ts +++ b/src/events/ready.ts @@ -5,7 +5,7 @@ import commands from '../commands/index.js' // Log when the bot successfully logs in and export it export default event(Events.ClientReady, ({ logger }, client) => { // Register the commands associated with the bot upon loggin in - registerCommands(client, commands) + registerCommands(client, commands, logger) // set status of the bot client.user.setActivity({ diff --git a/src/utils/commands.ts b/src/utils/commands.ts index 9afa17a..1a5972c 100644 --- a/src/utils/commands.ts +++ b/src/utils/commands.ts @@ -1,9 +1,6 @@ -import { ChatInputCommandInteraction, ChatInputApplicationCommandData, Client } from 'discord.js' -import { createLogger } from '../components/index.js' +import { ChatInputCommandInteraction, ChatInputApplicationCommandData, Client, type Awaitable } from 'discord.js' import type { Logger as PinoLogger } from 'pino' -const logger = createLogger({ component: 'commands' }) - /** * interface for how slash commands should be run */ @@ -12,7 +9,7 @@ export interface SlashCommand extends ChatInputApplicationCommandData { client: Client, interaction: ChatInputCommandInteraction, logger: PinoLogger - ) => void + ) => Awaitable } /** @@ -20,7 +17,7 @@ export interface SlashCommand extends ChatInputApplicationCommandData { * @param client the bot reference * @param commands commands to register to the bot */ -export function registerCommands(client: Client, commands: SlashCommand[]): void { +export function registerCommands(client: Client, commands: SlashCommand[], logger: PinoLogger): void { // ensure the bot is online before registering if (!client.application) return diff --git a/src/utils/handlers/chatHistoryHandler.ts b/src/utils/handlers/chatHistoryHandler.ts index 432bd8e..e542715 100644 --- a/src/utils/handlers/chatHistoryHandler.ts +++ b/src/utils/handlers/chatHistoryHandler.ts @@ -2,9 +2,7 @@ import { TextChannel, ThreadChannel } from 'discord.js' import { Configuration, Channel, UserMessage } from '../index.js' import fs from 'fs' import path from 'path' -import { createLogger } from '../../components/index.js' - -const logger = createLogger({ component: 'chat-history' }) +import type { Logger as PinoLogger } from 'pino' /** * Method to check if a thread history file exists @@ -32,7 +30,7 @@ async function checkChannelInfoExists(channel: TextChannel, user: string) { * @param user username of user * @returns nothing */ -export async function clearChannelInfo(filename: string, channel: TextChannel, user: string): Promise { +export async function clearChannelInfo(logger: PinoLogger, filename: string, channel: TextChannel, user: string): Promise { const channelInfoExists: boolean = await checkChannelInfoExists(channel, user) // If thread does not exist, file can't be found @@ -59,7 +57,7 @@ export async function clearChannelInfo(filename: string, channel: TextChannel, u return cleanedHistory } -export async function addToChannelContext(filename: string, channel: TextChannel | ThreadChannel, messages: UserMessage[] = []): Promise { +export async function addToChannelContext(logger: PinoLogger, filename: string, channel: TextChannel | ThreadChannel, messages: UserMessage[] = []): Promise { const fullFileName = `data/${filename}-context.json` if (fs.existsSync(fullFileName)) { fs.readFile(fullFileName, 'utf8', (error, data) => { @@ -115,7 +113,7 @@ export async function accessChannelContext(filename: string, callback: (config: * @param user the user's name * @param messages their messages */ -export async function openChannelInfo(filename: string, channel: TextChannel | ThreadChannel, user: string, messages: UserMessage[] = []): Promise { +export async function openChannelInfo(logger: PinoLogger, filename: string, channel: TextChannel | ThreadChannel, user: string, messages: UserMessage[] = []): Promise { const fullFileName = `data/${filename}-${user}.json` if (fs.existsSync(fullFileName)) { fs.readFile(fullFileName, 'utf8', (error, data) => { diff --git a/src/utils/handlers/configHandler.ts b/src/utils/handlers/configHandler.ts index b90ac59..54dc2f0 100644 --- a/src/utils/handlers/configHandler.ts +++ b/src/utils/handlers/configHandler.ts @@ -1,9 +1,7 @@ import { Configuration, ServerConfig, UserConfig, isServerConfigurationKey } from '../index.js' import fs from 'fs' import path from 'path' -import { createLogger } from '../../components/index.js' - -const logger = createLogger({ component: 'config' }) +import type { Logger as PinoLogger } from 'pino' /** * Method to open a file in the working directory and modify/create it @@ -13,7 +11,7 @@ const logger = createLogger({ component: 'config' }) * @param value new value to assign */ // add type of change (server, user) -export function openConfig(filename: string, key: string, value: any) { +export function openConfig(logger: PinoLogger, filename: string, key: string, value: any) { const fullFileName = `data/${filename}` // check if the file exists, if not then make the config file diff --git a/tests/logger.test.ts b/tests/logger.test.ts index 4da15dc..cceb58e 100644 --- a/tests/logger.test.ts +++ b/tests/logger.test.ts @@ -42,4 +42,23 @@ describe('Pino logger', () => { expect(entry.answer).toBe(42) expect(entry.msg).toBe('warning') }) + + it('preserves parent context when adding command bindings', () => { + output = '' + const eventLogger = createLogger({ + component: 'event', + event: 'InteractionCreate' + }, parentLogger) + const commandLogger = createLogger({ + component: 'command', + command: 'summary' + }, eventLogger) + + commandLogger.info('command started') + + const entry = JSON.parse(output) + expect(entry.component).toBe('command') + expect(entry.event).toBe('InteractionCreate') + expect(entry.command).toBe('summary') + }) }) diff --git a/tests/loggerIntegration.test.ts b/tests/loggerIntegration.test.ts new file mode 100644 index 0000000..06736c5 --- /dev/null +++ b/tests/loggerIntegration.test.ts @@ -0,0 +1,123 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Writable } from 'node:stream' +import { ChannelType, type ChatInputCommandInteraction, type Client, type TextChannel } from 'discord.js' +import pino from 'pino' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createLogger } from '../src/components/logger.js' +import { Capacity } from '../src/commands/capacity.js' +import { openChannelInfo } from '../src/utils/handlers/chatHistoryHandler.js' +import { registerCommands, type SlashCommand } from '../src/utils/commands.js' + +describe('logger context integration', () => { + let output = '' + const destination = new Writable({ + write(chunk, _encoding, callback) { + output += chunk.toString() + callback() + } + }) + const parentLogger = pino({ level: 'trace' }, destination) + let workingDirectory: string + let tempDirectory: string | undefined + + beforeEach(() => { + output = '' + workingDirectory = process.cwd() + vi.stubEnv('NODE_ENV', 'test') + }) + + afterEach(() => { + process.chdir(workingDirectory) + if (tempDirectory) + rmSync(tempDirectory, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('retains event and command context in registration and handler logs', async () => { + const readyLogger = createLogger({ + component: 'event', + event: 'ClientReady' + }, parentLogger) + const commandsApi = { + fetch: vi.fn().mockResolvedValue(new Map()), + cache: { clear: vi.fn() }, + create: vi.fn(async (command: SlashCommand) => ({ + name: command.name, + options: [] + })) + } + const client = { + application: { commands: commandsApi } + } as unknown as Client + const mockCommand = { + name: 'test-command', + description: 'test command', + run: vi.fn() + } as unknown as SlashCommand + + registerCommands(client, [mockCommand], readyLogger) + + const commandLogger = createLogger({ + component: 'command', + command: 'modify-capacity' + }, createLogger({ + component: 'event', + event: 'InteractionCreate' + }, parentLogger)) + const interaction = { + channelId: 'test-channel', + commandName: 'modify-capacity', + user: { username: 'test-user' }, + options: { + getNumber: () => 8, + get: () => ({ value: 8 }) + }, + reply: vi.fn() + } as unknown as ChatInputCommandInteraction + const commandClient = { + channels: { + fetch: vi.fn().mockResolvedValue({ type: ChannelType.GuildText }) + } + } as unknown as Client + + tempDirectory = mkdtempSync(join(tmpdir(), 'discord-ollama-logger-')) + process.chdir(tempDirectory) + + await Capacity.run(commandClient, interaction, commandLogger) + await openChannelInfo(commandLogger, 'test-channel', { + id: 'test-channel', + name: 'test' + } as TextChannel, 'test-user') + + await new Promise(resolve => setImmediate(resolve)) + const entries = output.trim().split('\n').map(line => JSON.parse(line)) + + const registration = entries.find(entry => entry.msg === 'Registered command on Discord') + expect(registration).toMatchObject({ + event: 'ClientReady', + command: 'test-command', + msg: 'Registered command on Discord' + }) + + const configuration = entries.find(entry => entry.msg === 'Created configuration file') + expect(configuration).toMatchObject({ + event: 'InteractionCreate', + component: 'command', + command: 'modify-capacity', + msg: 'Created configuration file' + }) + expect(configuration.caller).toMatch(/configHandler\.ts:\d+:\d+/) + + const history = entries.find(entry => entry.msg === 'Created channel history') + expect(history).toMatchObject({ + event: 'InteractionCreate', + component: 'command', + command: 'modify-capacity', + msg: 'Created channel history' + }) + expect(history.caller).toMatch(/chatHistoryHandler\.ts:\d+:\d+/) + + }) +})