Skip to content

Commit 120457d

Browse files
committed
feat: add logger
1 parent d8aa864 commit 120457d

File tree

11 files changed

+179
-44
lines changed

11 files changed

+179
-44
lines changed

apps/test-bot/src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,6 @@ const commandkit = new CommandKit({
1717
bulkRegister: true,
1818
});
1919

20+
commandkit.setPrefixResolver(() => ['!', '?']);
21+
2022
await client.login(process.env.TOKEN);

packages/commandkit/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
"dotenv": "^16.4.7",
3939
"ms": "^2.1.3",
4040
"ora": "^8.0.1",
41+
"picocolors": "^1.1.1",
4142
"rfdc": "^1.3.1",
4243
"rimraf": "^5.0.5",
4344
"tsup": "^8.3.5"

packages/commandkit/src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ export * from './context/async-context';
99
export * from './context/environment';
1010
export * from './cache/index';
1111
export * from './app/index';
12+
export * from './logger/DefaultLogger';
13+
export * from './logger/ILogger';
14+
export * from './logger/Logger';
1215
export type * from './types';
1316

1417
function $version(): string {

packages/commandkit/src/legacy/handlers/command-handler/CommandHandler.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
MiddlewareContext,
3131
} from '../../../app/commands/Context';
3232
import { CommandKitErrorCodes, isErrorType } from '../../../utils/error-codes';
33+
import { Logger } from '../../../logger/Logger';
3334

3435
export interface hCommandContext {
3536
interaction: CommandKitInteraction;
@@ -265,6 +266,8 @@ export class CommandHandler {
265266
messageCommandParser,
266267
});
267268

269+
environment.variables.set('currentCommandName', context.commandName);
270+
268271
const exec = async () => {
269272
if (middlewares.length > 0) {
270273
for (const middleware of middlewares) {
@@ -338,7 +341,7 @@ export class CommandHandler {
338341
}
339342
}
340343
} catch (e) {
341-
console.log(e);
344+
Logger.error(e);
342345
if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {
343346
postStageRunner = false;
344347
} else if (
@@ -391,18 +394,16 @@ export class CommandHandler {
391394
const time = `${env.getExecutionTime().toFixed(2)}ms`;
392395

393396
if (error) {
394-
console.error(
397+
Logger.error(
395398
colors.red(
396399
`[${marker} - ${time}] Error executing command: ${error.stack || error}`,
397400
),
398401
);
399402
return;
400403
}
401404

402-
console.log(
403-
colors.cyan('(app ✨)') +
404-
colors.reset(' ') +
405-
colors.green(`[${marker} - ${time}] Command executed successfully`),
405+
Logger.log(
406+
colors.green(`[${marker} - ${time}] Command executed successfully`),
406407
);
407408
});
408409

@@ -443,8 +444,13 @@ export class CommandHandler {
443444

444445
const env = useEnvironment();
445446

447+
env.variables.set('currentCommandName', interaction.commandName);
446448
env.variables.set('commandHandlerType', 'legacy');
447449
env.variables.set('interaction', interaction);
450+
env.variables.set(
451+
'execHandlerKind',
452+
isAutocomplete ? 'autocomplete' : 'chatInput',
453+
);
448454

449455
const { data, options, run, autocomplete, ...rest } = targetCommand;
450456

@@ -521,15 +527,15 @@ export class CommandHandler {
521527
const time = `${env.getExecutionTime().toFixed(2)}ms`;
522528

523529
if (error) {
524-
console.error(
530+
Logger.error(
525531
colors.red(
526532
`[${marker} - ${time}] Error executing command: ${error.stack || error}`,
527533
),
528534
);
529535
return;
530536
}
531537

532-
console.log(
538+
Logger.log(
533539
colors.green(`[${marker} - ${time}] Command executed successfully`),
534540
);
535541
});

packages/commandkit/src/legacy/handlers/command-handler/functions/loadCommandsWithRest.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { ApplicationCommandDataResolvable, Client } from 'discord.js';
22
import type { CommandFileObject, ReloadOptions } from '../../../../types';
33

44
import colors from '../../../../utils/colors';
5+
import { Logger } from '../../../../logger/Logger';
56

67
type LoadCommandsWithRestProps = {
78
/**
@@ -119,7 +120,7 @@ async function loadGlobalCommands(
119120
);
120121
});
121122

122-
console.log(
123+
Logger.log(
123124
colors.green(
124125
`${reloading ? 'Reloaded' : 'Loaded'} ${
125126
requestBody.length
@@ -172,7 +173,7 @@ async function loadDevCommands(
172173
);
173174
});
174175

175-
console.log(
176+
Logger.log(
176177
colors.green(
177178
`${reloading ? 'Reloaded' : 'Loaded'} ${
178179
requestBody.length

packages/commandkit/src/legacy/handlers/command-handler/functions/registerCommands.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { CommandFileObject, ReloadOptions } from '../../../../types';
1010
import areSlashCommandsDifferent from '../utils/areSlashCommandsDifferent';
1111

1212
import colors from '../../../../utils/colors';
13+
import { Logger } from '../../../../logger/Logger';
1314

1415
type RegisterCommandProps = {
1516
client: Client;
@@ -98,7 +99,7 @@ async function registerGlobalCommands(
9899
);
99100
});
100101

101-
console.log(
102+
Logger.log(
102103
colors.green(`Deleted command "${command.data.name}" globally.`),
103104
);
104105
}
@@ -125,7 +126,7 @@ async function registerGlobalCommands(
125126
);
126127
});
127128

128-
console.log(
129+
Logger.log(
129130
colors.green(`Edited command "${command.data.name}" globally.`),
130131
);
131132

@@ -147,7 +148,7 @@ async function registerGlobalCommands(
147148
);
148149
});
149150

150-
console.log(
151+
Logger.log(
151152
colors.green(`Registered command "${command.data.name}" globally.`),
152153
);
153154
}
@@ -209,7 +210,7 @@ async function registerDevCommands(
209210
);
210211
});
211212

212-
console.log(
213+
Logger.log(
213214
colors.green(
214215
`Deleted command "${command.data.name}" in ${guildCommands.guild.name}.`,
215216
),
@@ -238,7 +239,7 @@ async function registerDevCommands(
238239
);
239240
});
240241

241-
console.log(
242+
Logger.log(
242243
colors.green(
243244
`Edited command "${command.data.name}" in ${guildCommands.guild.name}.`,
244245
),
@@ -262,7 +263,7 @@ async function registerDevCommands(
262263
);
263264
});
264265

265-
console.log(
266+
Logger.log(
266267
colors.green(
267268
`Registered command "${command.data.name}" in ${guildCommands.guild.name}.`,
268269
),
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import { getContext } from '../context/async-context';
2+
import colors from '../utils/colors';
3+
import { ILogger } from './ILogger';
4+
5+
enum LogLevel {
6+
DEBUG,
7+
INFO,
8+
WARN,
9+
ERROR,
10+
DEFAULT,
11+
}
12+
13+
const execHandlerKind = {
14+
autocomplete: 'Autocomplete',
15+
messageContextMenu: 'MessageContextMenu',
16+
userContextMenu: 'UserContextMenu',
17+
chatInput: 'SlashCommand',
18+
message: 'Message',
19+
};
20+
21+
const commandHandlerType = {
22+
legacy: 'Legacy',
23+
app: 'App',
24+
};
25+
26+
export class DefaultLogger implements ILogger {
27+
private logger: Console;
28+
29+
public constructor(
30+
public stdout = process.stdout,
31+
public stderr = process.stderr,
32+
) {
33+
this.logger = new console.Console(this.stdout, this.stderr);
34+
}
35+
36+
private _getContext(): string {
37+
const ctx = getContext();
38+
if (!ctx) return '';
39+
40+
const kind = ctx.variables.get('execHandlerKind');
41+
const commandHandler = ctx.variables.get('commandHandlerType');
42+
const command = ctx.variables.get('currentCommandName');
43+
if (!kind && !commandHandler) return '';
44+
45+
const h = execHandlerKind[kind as keyof typeof execHandlerKind];
46+
47+
if (!h && !commandHandler) return '';
48+
49+
const t = commandHandler === 'app' ? '(app ✨) ' : '';
50+
51+
return `${colors.green(`${t}${command} ${h ? colors.gray(h) : ''}`.trim())}`;
52+
}
53+
54+
private _getPrefix(level: LogLevel): string {
55+
const timestamp = new Date().toISOString();
56+
const ctx = this._getContext();
57+
58+
switch (level) {
59+
case LogLevel.DEBUG:
60+
return `${colors.bgBlue(colors.black('[DEBUG]'))} | ${colors.gray(timestamp)} | ${ctx} - `;
61+
case LogLevel.INFO:
62+
return `${colors.bgGreen(colors.black('[INFO]'))} | ${colors.gray(timestamp)} | ${ctx} - `;
63+
case LogLevel.WARN:
64+
return `${colors.bgYellow(colors.black('[WARN]'))} | ${colors.gray(timestamp)} | ${ctx} - `;
65+
case LogLevel.ERROR:
66+
return `${colors.bgRed(colors.black('[ERROR]'))} | ${colors.gray(timestamp)} | ${ctx} - `;
67+
default:
68+
return `${colors.bgWhite(colors.black('[LOG]'))} | ${colors.gray(timestamp)} | ${ctx} - `;
69+
}
70+
}
71+
72+
private _log(level: LogLevel, ...args: any[]): void {
73+
const prefix = this._getPrefix(level);
74+
this.logger.log(prefix, ...args);
75+
}
76+
77+
public debug(...args: any[]): void {
78+
this._log(LogLevel.DEBUG, ...args);
79+
}
80+
81+
public error(...args: any[]): void {
82+
this._log(LogLevel.ERROR, ...args);
83+
}
84+
85+
public log(...args: any[]): void {
86+
this._log(LogLevel.DEFAULT, ...args);
87+
}
88+
89+
public info(...args: any[]): void {
90+
this._log(LogLevel.INFO, ...args);
91+
}
92+
93+
public warn(...args: any[]): void {
94+
this._log(LogLevel.WARN, ...args);
95+
}
96+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export interface ILogger {
2+
log(...args: any[]): void;
3+
error(...args: any[]): void;
4+
warn(...args: any[]): void;
5+
info(...args: any[]): void;
6+
debug(...args: any[]): void;
7+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { DefaultLogger } from './DefaultLogger';
2+
import { ILogger } from './ILogger';
3+
4+
export interface CommandKitLoggerOptions {
5+
/**
6+
* The logger provider to use.
7+
*/
8+
provider: ILogger;
9+
}
10+
11+
export interface LoggerImpl extends ILogger {
12+
configure(options: CommandKitLoggerOptions): void;
13+
}
14+
15+
export function createLogger(options: CommandKitLoggerOptions): LoggerImpl {
16+
let opt = options;
17+
18+
if (!opt?.provider) {
19+
throw new Error('A logger provider must be provided.');
20+
}
21+
22+
const methods = ['log', 'error', 'warn', 'info', 'debug'] as const;
23+
24+
const impl = {
25+
configure(options) {
26+
opt = options;
27+
},
28+
} as LoggerImpl;
29+
30+
for (const method of methods) {
31+
impl[method] = (...args: any[]) => {
32+
opt.provider[method](...args);
33+
};
34+
}
35+
36+
return impl;
37+
}
38+
39+
export const Logger = createLogger({
40+
provider: new DefaultLogger(),
41+
});
Lines changed: 2 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,3 @@
1-
const resetColor = '\x1b[0m';
1+
import { createColors } from 'picocolors';
22

3-
export default {
4-
reset: (text: string) => `${text}${resetColor}`,
5-
bright: (text: string) => `\x1b[1m${text}${resetColor}`,
6-
dim: (text: string) => `\x1b[2m${text}${resetColor}`,
7-
underscore: (text: string) => `\x1b[4m${text}${resetColor}`,
8-
blink: (text: string) => `\x1b[5m${text}${resetColor}`,
9-
reverse: (text: string) => `\x1b[7m${text}${resetColor}`,
10-
hidden: (text: string) => `\x1b[8m${text}${resetColor}`,
11-
12-
black: (text: string) => `\x1b[30m${text}${resetColor}`,
13-
red: (text: string) => `\x1b[31m${text}${resetColor}`,
14-
green: (text: string) => `\x1b[32m${text}${resetColor}`,
15-
yellow: (text: string) => `\x1b[33m${text}${resetColor}`,
16-
blue: (text: string) => `\x1b[34m${text}${resetColor}`,
17-
magenta: (text: string) => `\x1b[35m${text}${resetColor}`,
18-
cyan: (text: string) => `\x1b[36m${text}${resetColor}`,
19-
white: (text: string) => `\x1b[37m${text}${resetColor}`,
20-
21-
bgBlack: (text: string) => `\x1b[40m${text}${resetColor}`,
22-
bgRed: (text: string) => `\x1b[41m${text}${resetColor}`,
23-
bgGreen: (text: string) => `\x1b[42m${text}${resetColor}`,
24-
bgYellow: (text: string) => `\x1b[43m${text}${resetColor}`,
25-
bgBlue: (text: string) => `\x1b[44m${text}${resetColor}`,
26-
bgMagenta: (text: string) => `\x1b[45m${text}${resetColor}`,
27-
bgCyan: (text: string) => `\x1b[46m${text}${resetColor}`,
28-
bgWhite: (text: string) => `\x1b[47m${text}${resetColor}`,
29-
};
3+
export default createColors(true);

0 commit comments

Comments
 (0)