https://github.com/bebancode/commandkit-plugin-custom-logger
A CommandKit Runtime Plugin for advanced, file-based, and webhook logging.
https://github.com/bebancode/commandkit-plugin-custom-logger
commandkit commandkit-plugin logging logging-library
Last synced: 7 months ago
JSON representation
A CommandKit Runtime Plugin for advanced, file-based, and webhook logging.
- Host: GitHub
- URL: https://github.com/bebancode/commandkit-plugin-custom-logger
- Owner: BebanCode
- License: mit
- Created: 2025-07-12T18:23:53.000Z (10 months ago)
- Default Branch: master
- Last Pushed: 2025-07-14T16:08:43.000Z (10 months ago)
- Last Synced: 2025-08-16T11:58:26.950Z (8 months ago)
- Topics: commandkit, commandkit-plugin, logging, logging-library
- Language: TypeScript
- Homepage:
- Size: 30.3 KB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# CommandKit Plugin: Custom Logger
[](https://www.npmjs.com/package/commandkit-plugin-custom-logger)
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.
## Features
* **File Logging**: Automatically writes logs to files, organized in daily folders.
* **Log Rotation**: Prevents log files from growing indefinitely by automatically rotating them based on size and keeping a configurable number of backups.
* **Discord Webhook Integration**: Pushes important logs (like errors and fatals) directly to a Discord channel.
* **Customizable Console Output**: Rich, colorful console logging with customizable prefixes, colors, and timestamps.
* **CommandKit Integration**: Can seamlessly replace CommandKit's default internal logger to unify all logs in one place.
* **Standalone Usage**: Can be used as a standalone logger anywhere in your project.
* **Performance-conscious**: Features like caller info logging can be disabled to maximize performance.
## Installation
```bash
npm install commandkit-plugin-custom-logger
```
## Quick Start
To get started, register the plugin in your `commandkit.config.ts` file.
```ts
import { defineConfig } from 'commandkit';
import { LoggerPlugin } from 'commandkit-plugin-custom-logger';
export default defineConfig({
plugins: [
new LoggerPlugin(), // Use default settings
],
});
```
This is the simplest setup and will enable console logging and file logging to the `./logs` directory.
## Using the Logger
After initialization, you can import and use the logger functions anywhere in your project.
**File:** `/src/commands/myCommand.js`
```javascript
import { SlashCommandBuilder } from 'discord.js';
import { info, error, warn } from 'commandkit-plugin-logger'; // Adjust the import path
export const data = new SlashCommandBuilder()
.setName('my-command')
.setDescription('An example command.');
export const chatInput = async (ctx) => {
const { interaction } = ctx;
info(`User ${interaction.user.tag} ran the command.`);
try {
// Some logic that might fail
if (Math.random() > 0.5) {
throw new Error('Something went wrong!');
}
await interaction.reply('Command executed successfully!');
} catch (e) {
error('An error occurred in my-command:', e);
warn('This error was handled gracefully.');
await interaction.reply({
content: 'An error occurred, but it has been logged.',
ephemeral: true
});
}
}
```
## Configuration
You can customize the logger by passing an options object to the `LoggerPlugin` constructor.
### Example Configuration
```ts
import { defineConfig } from 'commandkit';
import { LoggerPlugin } from 'commandkit-plugin-logger';
export default defineConfig({
plugins: [
new LoggerPlugin({
// Send ERROR and FATAL logs to a Discord channel
webhookUrl: 'https://discord.com/api/webhooks/...',
webhookLogLevels: ['error', 'fatal'],
// Set console to only show INFO level and above
consoleLogLevel: 'info',
// Keep more log files
maxFileSizeMB: 20,
maxRotatedFiles: 10,
// Enable caller info for debugging
includeCallerInfo: true,
}),
],
});
```
### All Options
| Option | Type | Description | Default |
| :--- | :--- | :--- | :--- |
| `logDirectory` | `string` | The directory where log files will be stored. | `'./logs'` |
| `logFileName` | `string` | The base name for the log files. | `'app.log'` |
| `maxFileSizeMB` | `number` | The maximum size of a log file in MB before it is rotated. | `10` |
| `maxRotatedFiles` | `number` | The maximum number of rotated log files to keep. | `5` |
| `dateFormat` | `string` | The [Moment.js](https://momentjs.com/docs/#/displaying/format/) format for daily log folder names. | `'YYYY-MM-DD'` |
| `timestampFormat` | `string` | The Moment.js format for timestamps in log entries. | `'YYYY-MM-DD HH:mm:ss.SSS'` |
| `consoleLogLevel` | `LogLevel` | Minimum log level for the console (`debug`, `info`, `warn`, etc.). | `'debug'` |
| `fileLogLevel` | `LogLevel` | Minimum log level for the log file. | `'debug'` |
| `webhookUrl` | `string \| null` | The URL of the Discord webhook to send logs to. | `null` |
| `webhookLogLevels`| `LogLevel[]` | An array of log levels that should trigger a webhook message. | `['error', 'fatal']` |
| `includeCallerInfo` | `boolean` | Includes the caller's file path and line number in logs. **Can impact performance.** | `false` |
| `replaceCommandKitLogger` | `boolean` | Replaces CommandKit's internal logger with this one to unify logs. | `true` |
| `commandKitLogPrefix` | `string` | The prefix to use for logs originating from CommandKit's internal logger. | `'[CK]'` |
| `colors` | `object` | Custom color mappings for log levels in the console. | (See defaults) |
| `prefixes` | `object` | Custom prefix strings for log levels. | (See defaults) |
## API Reference
The plugin exports several functions for direct use:
* `info(...args: any[]): void`
* `warn(...args: any[]): void`
* `error(...args: any[]): void`
* `debug(...args: any[]): void`
* `fatal(...args: any[]): void`
* `success(...args: any[]): void`
* `log(level: string, ...args: any[]): void` - Logs with a dynamic level.
* `closeLogger(): Promise` - Gracefully closes file streams and webhook clients.
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.