aboutsummaryrefslogtreecommitdiff
path: root/src/lib/utils/BushLogger.ts
blob: 1be58a429c250bf20c8e81623e8428fe1afdbbef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import chalk from 'chalk';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Client, EmbedBuilder, escapeMarkdown, PartialTextBasedChannelFields, type Message } from 'discord.js';
import repl, { REPLServer, REPL_MODE_STRICT } from 'repl';
import { WriteStream } from 'tty';
import { type SendMessageType } from '../extensions/discord-akairo/BushClient.js';
import { colors } from './BushConstants.js';
import { inspect } from './BushUtils.js';

let REPL: REPLServer;
let replGone = false;

export function init() {
	const kFormatForStdout = Object.getOwnPropertySymbols(console).find((sym) => sym.toString() === 'Symbol(kFormatForStdout)')!;
	const kFormatForStderr = Object.getOwnPropertySymbols(console).find((sym) => sym.toString() === 'Symbol(kFormatForStderr)')!;

	REPL = repl.start({
		useColors: true,
		terminal: true,
		useGlobal: true,
		replMode: REPL_MODE_STRICT,
		breakEvalOnSigint: true,
		ignoreUndefined: true
	});

	const apply = (stream: WriteStream, symbol: symbol): ProxyHandler<typeof console['log']>['apply'] =>
		function apply(target, thisArg, args) {
			if (stream.isTTY) {
				stream.moveCursor(0, -1);
				stream.write('\n');
				stream.clearLine(0);
			}

			const ret = target(...args);

			if (stream.isTTY) {
				const formatted = (console as any)[symbol](args) as string;

				stream.moveCursor(0, formatted.split('\n').length);
				if (!replGone) {
					REPL.displayPrompt(true);
				}
			}

			return ret;
		};

	global.console.log = new Proxy(console.log, {
		apply: apply(process.stdout, kFormatForStdout)
	});

	global.console.warn = new Proxy(console.warn, {
		apply: apply(process.stderr, kFormatForStderr)
	});

	REPL.on('exit', () => {
		replGone = true;
		process.exit(0);
	});
}

/**
 * Parses the content surrounding by `<<>>` and emphasizes it with the given color or by making it bold.
 * @param content The content to parse.
 * @param color The color to emphasize the content with.
 * @param discordFormat Whether or not to format the content for discord.
 * @returns The formatted content.
 */
function parseFormatting(
	content: any,
	color: 'blueBright' | 'blackBright' | 'redBright' | 'yellowBright' | 'greenBright' | '',
	discordFormat = false
): string | typeof content {
	if (typeof content !== 'string') return content;
	const newContent: Array<string> = content.split(/<<|>>/);
	const tempParsedArray: Array<string> = [];
	newContent.forEach((value, index) => {
		if (index % 2 !== 0) {
			tempParsedArray.push(discordFormat ? `**${escapeMarkdown(value)}**` : color ? chalk[color](value) : value);
		} else {
			tempParsedArray.push(discordFormat ? escapeMarkdown(value) : value);
		}
	});
	return tempParsedArray.join('');
}

/**
 * Inspects the content and returns a string.
 * @param content The content to inspect.
 * @param depth The depth the content will inspected. Defaults to `2`.
 * @param colors Whether or not to use colors in the output. Defaults to `true`.
 * @returns The inspected content.
 */
function inspectContent(content: any, depth = 2, colors = true): string {
	if (typeof content !== 'string') {
		return inspect(content, { depth, colors });
	}
	return content;
}

/**
 * Strips ANSI color codes from a string.
 * @param text The string to strip color codes from.
 * @returns A string without ANSI color codes.
 */
function stripColor(text: string): string {
	return text.replace(
		// eslint-disable-next-line no-control-regex
		/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
		''
	);
}

/**
 * Generates a formatted timestamp for logging.
 * @returns The formatted timestamp.
 */
function getTimeStamp(): string {
	const now = new Date();
	const hours = now.getHours();
	const minute = now.getMinutes();
	let hour = hours;
	let amOrPm: 'AM' | 'PM' = 'AM';
	if (hour > 12) {
		amOrPm = 'PM';
		hour = hour - 12;
	}
	return `${hour >= 10 ? hour : `0${hour}`}:${minute >= 10 ? minute : `0${minute}`} ${amOrPm}`;
}

/**
 * Custom logging utility for the bot.
 */
export class BushLogger {
	public constructor(
		/**
		 * The client.
		 */
		public client: Client
	) {}

	/**
	 * Logs information. Highlight information by surrounding it in `<<>>`.
	 * @param header The header displayed before the content, displayed in cyan.
	 * @param content The content to log, highlights displayed in bright blue.
	 * @param sendChannel Should this also be logged to discord? Defaults to false.
	 * @param depth The depth the content will inspected. Defaults to 0.
	 */
	public get log() {
		return this.info;
	}

	/**
	 * Sends a message to the log channel.
	 * @param message The parameter to pass to {@link PartialTextBasedChannelFields.send}.
	 * @returns The message sent.
	 */
	public async channelLog(message: SendMessageType): Promise<Message | null> {
		const channel = await this.client.utils.getConfigChannel('log');
		return await channel.send(message).catch(() => null);
	}

	/**
	 * Sends a message to the error channel.
	 * @param message The parameter to pass to {@link PartialTextBasedChannelFields.send}.
	 * @returns The message sent.
	 */
	public async channelError(message: SendMessageType): Promise<Message | null> {
		const channel = await this.client.utils.getConfigChannel('error');
		if (!channel) {
			void this.error(
				'BushLogger',
				`Could not find error channel, was originally going to send: \n${inspect(message, {
					colors: true
				})}\n${new Error().stack?.substring(8)}`,
				false
			);
			return null;
		}
		return await channel.send(message);
	}

	/**
	 * Logs debug information. Only works in dev is enabled in the config.
	 * @param content The content to log.
	 * @param depth The depth the content will inspected. Defaults to `0`.
	 */
	public debug(content: any, depth = 0): void {
		if (!this.client.config.isDevelopment) return;
		const newContent = inspectContent(content, depth, true);
		console.log(`${chalk.bgMagenta(getTimeStamp())} ${chalk.magenta('[Debug]')} ${newContent}`);
	}

	/**
	 * Logs raw debug information. Only works in dev is enabled in the config.
	 * @param content The content to log.
	 */
	public debugRaw(...content: any): void {
		if (!this.client.config.isDevelopment) return;
		console.log(`${chalk.bgMagenta(getTimeStamp())} ${chalk.magenta('[Debug]')}`, ...content);
	}

	/**
	 * Logs verbose information. Highlight information by surrounding it in `<<>>`.
	 * @param header The header printed before the content, displayed in grey.
	 * @param content The content to log, highlights displayed in bright black.
	 * @param sendChannel Should this also be logged to discord? Defaults to `false`.
	 * @param depth The depth the content will inspected. Defaults to `0`.
	 */
	public async verbose(header: string, content: any, sendChannel = false, depth = 0): Promise<void> {
		if (!this.client.config.logging.verbose) return;
		const newContent = inspectContent(content, depth, true);
		console.log(`${chalk.bgGrey(getTimeStamp())} ${chalk.grey(`[${header}]`)} ${parseFormatting(newContent, 'blackBright')}`);
		if (!sendChannel) return;
		const embed = new EmbedBuilder()
			.setDescription(`**[${header}]** ${parseFormatting(stripColor(newContent), '', true)}`)
			.setColor(colors.gray)
			.setTimestamp();
		await this.channelLog({ embeds: [embed] });
	}

	/**
	 * Logs very verbose information. Highlight information by surrounding it in `<<>>`.
	 * @param header The header printed before the content, displayed in purple.
	 * @param content The content to log, highlights displayed in bright black.
	 * @param depth The depth the content will inspected. Defaults to `0`.
	 */
	public async superVerbose(header: string, content: any, depth = 0): Promise<void> {
		if (!this.client.config.logging.verbose) return;
		const newContent = inspectContent(content, depth, true);
		console.log(
			`${chalk.bgHex('#949494')(getTimeStamp())} ${chalk.hex('#949494')(`[${header}]`)} ${chalk.hex('#b3b3b3')(newContent)}`
		);
	}

	/**
	 * Logs raw very verbose information.
	 * @param header The header printed before the content, displayed in purple.
	 * @param content The content to log.
	 */
	public async superVerboseRaw(header: string, ...content: any[]): Promise<void> {
		if (!this.client.config.logging.verbose) return;
		console.log(`${chalk.bgHex('#a3a3a3')(getTimeStamp())} ${chalk.hex('#a3a3a3')(`[${header}]`)}`, ...content);
	}

	/**
	 * Logs information. Highlight information by surrounding it in `<<>>`.
	 * @param header The header displayed before the content, displayed in cyan.
	 * @param content The content to log, highlights displayed in bright blue.
	 * @param sendChannel Should this also be logged to discord? Defaults to `false`.
	 * @param depth The depth the content will inspected. Defaults to `0`.
	 */
	public async info(header: string, content: any, sendChannel = true, depth = 0): Promise<void> {
		if (!this.client.config.logging.info) return;
		const newContent = inspectContent(content, depth, true);
		console.log(`${chalk.bgCyan(getTimeStamp())} ${chalk.cyan(`[${header}]`)} ${parseFormatting(newContent, 'blueBright')}`);
		if (!sendChannel) return;
		const embed = new EmbedBuilder()
			.setDescription(`**[${header}]** ${parseFormatting(stripColor(newContent), '', true)}`)
			.setColor(colors.info)
			.setTimestamp();
		await this.channelLog({ embeds: [embed] });
	}

	/**
	 * Logs warnings. Highlight information by surrounding it in `<<>>`.
	 * @param header The header displayed before the content, displayed in yellow.
	 * @param content The content to log, highlights displayed in bright yellow.
	 * @param sendChannel Should this also be logged to discord? Defaults to `false`.
	 * @param depth The depth the content will inspected. Defaults to `0`.
	 */
	public async warn(header: string, content: any, sendChannel = true, depth = 0): Promise<void> {
		const newContent = inspectContent(content, depth, true);
		console.warn(
			`${chalk.bgYellow(getTimeStamp())} ${chalk.yellow(`[${header}]`)} ${parseFormatting(newContent, 'yellowBright')}`
		);

		if (!sendChannel) return;
		const embed = new EmbedBuilder()
			.setDescription(`**[${header}]** ${parseFormatting(stripColor(newContent), '', true)}`)
			.setColor(colors.warn)
			.setTimestamp();
		await this.channelError({ embeds: [embed] });
	}

	/**
	 * Logs errors. Highlight information by surrounding it in `<<>>`.
	 * @param header The header displayed before the content, displayed in bright red.
	 * @param content The content to log, highlights displayed in bright red.
	 * @param sendChannel Should this also be logged to discord? Defaults to `false`.
	 * @param depth The depth the content will inspected. Defaults to `0`.
	 */
	public async error(header: string, content: any, sendChannel = true, depth = 0): Promise<void> {
		const newContent = inspectContent(content, depth, true);
		console.warn(
			`${chalk.bgRedBright(getTimeStamp())} ${chalk.redBright(`[${header}]`)} ${parseFormatting(newContent, 'redBright')}`
		);
		if (!sendChannel) return;
		const embed = new EmbedBuilder()
			.setDescription(`**[${header}]** ${parseFormatting(stripColor(newContent), '', true)}`)
			.setColor(colors.error)
			.setTimestamp();
		await this.channelError({ embeds: [embed] });
		return;
	}

	/**
	 * Logs successes. Highlight information by surrounding it in `<<>>`.
	 * @param header The header displayed before the content, displayed in green.
	 * @param content The content to log, highlights displayed in bright green.
	 * @param sendChannel Should this also be logged to discord? Defaults to `false`.
	 * @param depth The depth the content will inspected. Defaults to `0`.
	 */
	public async success(header: string, content: any, sendChannel = true, depth = 0): Promise<void> {
		const newContent = inspectContent(content, depth, true);
		console.log(
			`${chalk.bgGreen(getTimeStamp())} ${chalk.greenBright(`[${header}]`)} ${parseFormatting(newContent, 'greenBright')}`
		);
		if (!sendChannel) return;
		const embed = new EmbedBuilder()
			.setDescription(`**[${header}]** ${parseFormatting(stripColor(newContent), '', true)}`)
			.setColor(colors.success)
			.setTimestamp();
		await this.channelLog({ embeds: [embed] }).catch(() => {});
	}
}

/** @typedef {PartialTextBasedChannelFields} vscodeDontDeleteMyImportTy */