|
| 1 | +# CommandKit Plugin: Custom Logger |
| 2 | + |
| 3 | +[](https://www.npmjs.com/package/commandkit-plugin-custom-logger) |
| 4 | + |
| 5 | +A powerful, feature-rich logging plugin for [CommandKit](https://commandkit.dev) that offers file logging, log rotation, Discord webhook integration, and highly customizable console output. |
| 6 | + |
| 7 | +## Features |
| 8 | + |
| 9 | +* **File Logging**: Automatically writes logs to files, organized in daily folders. |
| 10 | +* **Log Rotation**: Prevents log files from growing indefinitely by automatically rotating them based on size and keeping a configurable number of backups. |
| 11 | +* **Discord Webhook Integration**: Pushes important logs (like errors and fatals) directly to a Discord channel. |
| 12 | +* **Customizable Console Output**: Rich, colorful console logging with customizable prefixes, colors, and timestamps. |
| 13 | +* **CommandKit Integration**: Can seamlessly replace CommandKit's default internal logger to unify all logs in one place. |
| 14 | +* **Standalone Usage**: Can be used as a standalone logger anywhere in your project. |
| 15 | +* **Performance-conscious**: Features like caller info logging can be disabled to maximize performance. |
| 16 | + |
| 17 | +## Installation |
| 18 | + |
| 19 | +```bash |
| 20 | +npm install commandkit-plugin-custom-logger |
| 21 | +``` |
| 22 | + |
| 23 | +## Quick Start |
| 24 | + |
| 25 | +To get started, register the plugin in your `commandkit.config.ts` file. |
| 26 | + |
| 27 | +```ts |
| 28 | +import { defineConfig } from 'commandkit'; |
| 29 | +import { LoggerPlugin } from 'commandkit-plugin-custom-logger'; |
| 30 | + |
| 31 | +export default defineConfig({ |
| 32 | + plugins: [ |
| 33 | + new LoggerPlugin(), // Use default settings |
| 34 | + ], |
| 35 | +}); |
| 36 | +``` |
| 37 | + |
| 38 | +This is the simplest setup and will enable console logging and file logging to the `./logs` directory. |
| 39 | + |
| 40 | +## Using the Logger |
| 41 | + |
| 42 | +After initialization, you can import and use the logger functions anywhere in your project. |
| 43 | + |
| 44 | +**File:** `/src/commands/myCommand.js` |
| 45 | +```javascript |
| 46 | +import { SlashCommandBuilder } from 'discord.js'; |
| 47 | +import { info, error, warn } from 'commandkit-plugin-logger'; // Adjust the import path |
| 48 | + |
| 49 | +export const data = new SlashCommandBuilder() |
| 50 | + .setName('my-command') |
| 51 | + .setDescription('An example command.'); |
| 52 | + |
| 53 | +export const chatInput = async (ctx) => { |
| 54 | + const { interaction } = ctx; |
| 55 | + |
| 56 | + info(`User ${interaction.user.tag} ran the command.`); |
| 57 | + |
| 58 | + try { |
| 59 | + // Some logic that might fail |
| 60 | + if (Math.random() > 0.5) { |
| 61 | + throw new Error('Something went wrong!'); |
| 62 | + } |
| 63 | + await interaction.reply('Command executed successfully!'); |
| 64 | + } catch (e) { |
| 65 | + error('An error occurred in my-command:', e); |
| 66 | + warn('This error was handled gracefully.'); |
| 67 | + await interaction.reply({ |
| 68 | + content: 'An error occurred, but it has been logged.', |
| 69 | + ephemeral: true |
| 70 | + }); |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +## Configuration |
| 76 | + |
| 77 | +You can customize the logger by passing an options object to the `LoggerPlugin` constructor. |
| 78 | + |
| 79 | +### Example Configuration |
| 80 | + |
| 81 | +```ts |
| 82 | +import { defineConfig } from 'commandkit'; |
| 83 | +import { LoggerPlugin } from 'commandkit-plugin-logger'; |
| 84 | + |
| 85 | +export default defineConfig({ |
| 86 | + plugins: [ |
| 87 | + new LoggerPlugin({ |
| 88 | + // Send ERROR and FATAL logs to a Discord channel |
| 89 | + webhookUrl: 'https://discord.com/api/webhooks/...', |
| 90 | + webhookLogLevels: ['error', 'fatal'], |
| 91 | + |
| 92 | + // Set console to only show INFO level and above |
| 93 | + consoleLogLevel: 'info', |
| 94 | + |
| 95 | + // Keep more log files |
| 96 | + maxFileSizeMB: 20, |
| 97 | + maxRotatedFiles: 10, |
| 98 | + |
| 99 | + // Enable caller info for debugging |
| 100 | + includeCallerInfo: true, |
| 101 | + }), |
| 102 | + ], |
| 103 | +}); |
| 104 | +``` |
| 105 | + |
| 106 | +### All Options |
| 107 | + |
| 108 | +| Option | Type | Description | Default | |
| 109 | +| :--- | :--- | :--- | :--- | |
| 110 | +| `logDirectory` | `string` | The directory where log files will be stored. | `'./logs'` | |
| 111 | +| `logFileName` | `string` | The base name for the log files. | `'app.log'` | |
| 112 | +| `maxFileSizeMB` | `number` | The maximum size of a log file in MB before it is rotated. | `10` | |
| 113 | +| `maxRotatedFiles` | `number` | The maximum number of rotated log files to keep. | `5` | |
| 114 | +| `dateFormat` | `string` | The [Moment.js](https://momentjs.com/docs/#/displaying/format/) format for daily log folder names. | `'YYYY-MM-DD'` | |
| 115 | +| `timestampFormat` | `string` | The Moment.js format for timestamps in log entries. | `'YYYY-MM-DD HH:mm:ss.SSS'` | |
| 116 | +| `consoleLogLevel` | `LogLevel` | Minimum log level for the console (`debug`, `info`, `warn`, etc.). | `'debug'` | |
| 117 | +| `fileLogLevel` | `LogLevel` | Minimum log level for the log file. | `'debug'` | |
| 118 | +| `webhookUrl` | `string \| null` | The URL of the Discord webhook to send logs to. | `null` | |
| 119 | +| `webhookLogLevels`| `LogLevel[]` | An array of log levels that should trigger a webhook message. | `['error', 'fatal']` | |
| 120 | +| `includeCallerInfo` | `boolean` | Includes the caller's file path and line number in logs. **Can impact performance.** | `false` | |
| 121 | +| `replaceCommandKitLogger` | `boolean` | Replaces CommandKit's internal logger with this one to unify logs. | `true` | |
| 122 | +| `commandKitLogPrefix` | `string` | The prefix to use for logs originating from CommandKit's internal logger. | `'[CK]'` | |
| 123 | +| `colors` | `object` | Custom color mappings for log levels in the console. | (See defaults) | |
| 124 | +| `prefixes` | `object` | Custom prefix strings for log levels. | (See defaults) | |
| 125 | + |
| 126 | +## API Reference |
| 127 | + |
| 128 | +The plugin exports several functions for direct use: |
| 129 | + |
| 130 | +* `info(...args: any[]): void` |
| 131 | +* `warn(...args: any[]): void` |
| 132 | +* `error(...args: any[]): void` |
| 133 | +* `debug(...args: any[]): void` |
| 134 | +* `fatal(...args: any[]): void` |
| 135 | +* `success(...args: any[]): void` |
| 136 | +* `log(level: string, ...args: any[]): void` - Logs with a dynamic level. |
| 137 | +* `closeLogger(): Promise<void>` - Gracefully closes file streams and webhook clients. |
| 138 | + |
| 139 | +## License |
| 140 | + |
| 141 | +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details. |
0 commit comments