galactic-bot/archive/Logger.js

191 lines
5.1 KiB
JavaScript
Raw Permalink Normal View History

2022-01-27 00:11:14 +01:00
/* eslint-disable max-len */
2021-08-16 23:01:08 +02:00
const chalk = require('chalk');
const moment = require('moment');
const path = require('path');
const fs = require('fs');
2022-03-26 21:08:13 +01:00
const { WebhookClient } = require('discord.js');
const os = require('os');
const { username } = os.userInfo();
2021-08-16 23:01:08 +02:00
const { Util } = require('../src/utilities');
2021-08-16 23:01:08 +02:00
const Constants = {
Types: [
'error',
'warn',
'info',
'debug',
'status'
],
Colors: {
error: 'red',
warn: 'yellow',
info: 'blue',
debug: 'magenta',
status: 'cyanBright'
2022-07-14 00:24:46 +02:00
},
ColorCodes: {
error: 0xe88388,
warn: 0xf9d472,
info: 0x76a9d8,
debug: 0xd8abd7,
status: 0x72d4d7
2021-08-16 23:01:08 +02:00
}
};
2023-06-22 01:07:19 +02:00
const stripRegex = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/gu; // eslint-disable-line no-control-regex
2021-08-16 23:01:08 +02:00
class Logger
{
2021-08-16 23:01:08 +02:00
constructor (manager, options)
{
2021-08-16 23:01:08 +02:00
this.manager = manager;
this.shardingManager = manager.shardingManager;
2022-05-04 01:26:32 +02:00
const { ERROR_WEBHOOK_URL } = process.env;
2023-06-22 01:07:19 +02:00
if (ERROR_WEBHOOK_URL)
this._webhook = new WebhookClient({ url: ERROR_WEBHOOK_URL });
2022-05-04 01:26:32 +02:00
// eslint-disable-next-line no-console
2023-06-22 01:07:19 +02:00
else
console.log('No webhook for logger');
2022-03-26 21:08:13 +01:00
2021-08-16 23:01:08 +02:00
this._options = options;
this._writeStream = this._loadFile();
this._errorWriteStream = this._loadFile('error');
this.shardingManager
.on('shardCreate', (shard) =>
{
this.write('info', 'Shard created.', shard);
2021-08-16 23:01:08 +02:00
});
}
write (type = 'info', string = '', shard = null, api = false, broadcast = false)
{
2021-08-16 23:01:08 +02:00
2023-06-22 01:07:19 +02:00
if (string.includes('ECONNRESET'))
return;
2022-09-16 16:31:26 +02:00
2021-08-16 23:01:08 +02:00
type = type.toLowerCase();
let color = Constants.Colors[type];
2023-06-22 01:07:19 +02:00
if (!color)
color = Constants.Colors.info;
2021-08-16 23:01:08 +02:00
2021-08-25 22:15:54 +02:00
const header = `${chalk[color](`[${Util.date}][${shard ? `${api ? 'api-s' : 'shard'}${this._shardId(shard)}` : `${api ? 'api-man' : 'manager'}`}]`)}`;
2021-08-16 23:01:08 +02:00
const maximumCharacters = Math.max(...Constants.Types.map((t) => t.length));
const spacers = maximumCharacters - type.length;
const text = `${chalk[color](type)}${' '.repeat(spacers)} ${header}: ${string}`;
2022-03-26 21:08:13 +01:00
const strippedText = text.replace(stripRegex, '');
2021-08-16 23:01:08 +02:00
2023-06-22 01:07:19 +02:00
console.log(text); // eslint-disable-line no-console
if (type === 'error' || broadcast)
this.webhook(strippedText, type);
2021-08-16 23:01:08 +02:00
2022-03-26 21:08:13 +01:00
const stream = type === 'error' ? '_errorWriteStream' : '_writeStream';
if (this[stream])
{
2022-03-26 21:08:13 +01:00
this[stream]
2021-08-16 23:01:08 +02:00
.write(`\n${strippedText}`);
}
}
webhook (text, type)
{
2022-03-26 21:08:13 +01:00
2023-06-22 01:07:19 +02:00
if (!this._webhook)
return;
2022-03-26 21:08:13 +01:00
const message = text.replace(new RegExp(process.env.DISCORD_TOKEN, 'gu'), '<redacted>')
.replace(new RegExp(username, 'gu'), '<redacted>');
const embed = {
2022-07-14 00:24:46 +02:00
color: Constants.ColorCodes[type],
2022-03-26 21:08:13 +01:00
timestamp: new Date(),
2022-05-04 01:26:32 +02:00
description: `\`\`\`${message.length > 2000 ? message.substring(0, 2000) + ' ... CONTENT CUT OFF' : message}\`\`\``,
2022-03-26 21:08:13 +01:00
};
2023-06-22 01:07:19 +02:00
this._webhook.send({ embeds: [ embed ], username: `ENV: ${process.env.NODE_ENV}` });
2022-03-26 21:08:13 +01:00
}
_loadFile (type = null)
{
2021-08-16 23:01:08 +02:00
const filename = `${moment().format('YYYY-MM-DD')}${type ? `-${type}` : ''}`;
const directory = path.join(process.cwd(), this._options.directory);
2023-06-22 01:07:19 +02:00
// Ensuring that the log folders exist.
if (!fs.existsSync(directory))
fs.mkdirSync(directory);
2021-08-16 23:01:08 +02:00
2023-06-22 01:07:19 +02:00
// Creating the log files.
2021-08-16 23:01:08 +02:00
const filepath = path.join(directory, `${filename}.log`);
let filedirectory = null;
if (!fs.existsSync(filepath))
{
2021-08-16 23:01:08 +02:00
fs.writeFileSync(filepath, '');
filedirectory = filepath;
this.write('debug', `Creating new${type ? ` ${type} ` : ' '}log file at: ${chalk.bold(`"${filepath}"`)}`);
}
else
{
2021-08-16 23:01:08 +02:00
this.write('debug', `Found existing${type ? ` ${type} ` : ' '}log file, using: ${chalk.bold(`"${filepath}"`)}`);
filedirectory = filepath;
}
if (filedirectory)
{
2023-06-22 01:07:19 +02:00
return fs.createWriteStream(filedirectory, { flags: 'a' }); // Appends to file.
2021-08-16 23:01:08 +02:00
}
this.write('error', 'Unable to open write stream for log file, proceeding without one.');
2021-08-16 23:01:08 +02:00
return null;
}
2023-06-22 01:07:19 +02:00
// Messages coming from the shards process.send functions.
_handleMessage (shard, message)
{
2022-07-14 00:24:46 +02:00
this.write(message.type, message.message, shard, message._api, message.broadcast);
2021-08-16 23:01:08 +02:00
}
_shardId (shard)
{
2021-08-16 23:01:08 +02:00
const { id } = shard;
return `${id}`.length === 1 ? `0${id}` : `${id}`;
}
error (message)
{
2021-08-25 22:15:15 +02:00
this.write('error', message);
}
warn (message)
{
2021-08-25 22:15:15 +02:00
this.write('warn', message);
}
debug (message)
{
2021-08-25 22:15:15 +02:00
this.write('debug', message);
}
info (message)
{
2021-08-25 22:15:15 +02:00
this.write('info', message);
}
status (message)
{
2021-08-25 22:15:15 +02:00
this.write('status', message);
}
2021-08-16 23:01:08 +02:00
}
export default Logger;