galactic-bot/middleware/logger/Logger.js

78 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-04-14 08:41:42 +02:00
const { createLogger, format, transports: { Console }, config } = require('winston');
const moment = require('moment');
2020-04-12 14:34:35 +02:00
const chalk = require('chalk');
2020-04-08 16:27:34 +02:00
2020-04-14 05:25:17 +02:00
const { DiscordWebhook, FileExtension } = require('./transports/');
2020-04-13 22:38:10 +02:00
const Constants = {
Colors: {
error: 'red',
warn: 'yellow',
info: 'blue',
verbose: 'cyan',
debug: 'magenta',
silly: 'magentaBright'
}
};
2020-04-09 16:30:52 +02:00
class Logger {
2020-04-08 16:27:34 +02:00
2020-04-09 16:30:52 +02:00
constructor(manager) {
this.manager = manager;
2020-04-13 22:38:10 +02:00
this.shardManager = manager.shardManager;
2020-04-12 14:34:35 +02:00
this.logger = createLogger({
2020-04-14 05:25:17 +02:00
levels: config.npm.levels,
format:
2020-04-14 05:25:17 +02:00
format.cli({
colors: Constants.Colors
}),
transports: [
new FileExtension({ filename: `logs/${this.date.split(' ')[0]}.log`, level: 'debug' }), //Will NOT log "silly" logs, could change in future.
new FileExtension({ filename: `logs/errors/${this.date.split(' ')[0]}-error.log`, level: 'error' }),
2020-04-14 08:41:42 +02:00
new Console({ level: 'silly' }), //Will log EVERYTHING.
2020-04-13 22:38:10 +02:00
new DiscordWebhook({ level: 'error' }) //Broadcast errors to a discord webhook.
]
});
2020-04-09 16:30:52 +02:00
2020-04-14 05:25:17 +02:00
//TODO: Add proper date-oriented filenames and add a daily rotation file (?).
2020-04-13 22:38:10 +02:00
this.shardManager
2020-08-13 22:44:58 +02:00
.on('shardCreate', (shard) => this.write('info', "Shard created.", shard));
process.on("unhandledRejection", (error) => {
this.write('error', `Unhandled promise rejection:\n${error.stack}`); //eslint-disable-line no-console
});
2020-04-12 14:34:35 +02:00
}
2020-04-14 08:41:42 +02:00
write(type = 'silly', string = '', shard = null) {
2020-04-12 14:34:35 +02:00
2020-04-13 22:38:10 +02:00
const color = Constants.Colors[type];
2020-04-14 05:25:17 +02:00
const header = `${chalk[color](`[${this.date}][${shard ? `shard${this._shardId(shard)}` : 'manager'}]`)}`;
2020-04-12 14:34:35 +02:00
2020-04-14 05:25:17 +02:00
this.logger.log(type, `${header} : ${string}`);
2020-04-12 14:34:35 +02:00
}
//Messages coming from the shards process.send functions.
_handleMessage(shard, message) {
this.write(message.type, message.message, shard);
}
2020-04-12 14:34:35 +02:00
_shardId(shard) {
const { id } = shard;
2020-04-12 14:34:35 +02:00
return `${id}`.length === 1 ? `0${id}` : `${id}`;
2020-04-09 16:30:52 +02:00
}
2020-04-08 16:27:34 +02:00
get date() {
return moment().format("YYYY-MM-DD hh:mm:ss");
}
2020-04-08 16:27:34 +02:00
}
module.exports = Logger;