galactic-bot/middleware/logger/Logger.js

78 lines
2.2 KiB
JavaScript

const { createLogger, format, transports: { Console }, config } = require('winston');
const { combine, label, printf } = format;
const moment = require('moment');
const chalk = require('chalk');
const { stripIndents } = require('common-tags');
const { DiscordWebhook, FileExtension } = require('./transports/');
class Logger {
constructor(manager) {
this.manager = manager;
this.shardManager = manager.shardManager;
this.logger = createLogger({
levels: config.npm.levels,
format: (
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' }),
new Console({ level: 'silly' }), //Will log EVERYTHING.
new DiscordWebhook({ level: 'error' }) //Broadcast errors to a discord webhook.
]
});
//TODO: Add proper date-oriented filenames and add a daily rotation file (?).
this.shardManager
.on('shardCreate', (shard) => this.write('debug', "Shard created.", shard))
}
write(type = 'silly', string = '', shard = null) {
const color = Constants.Colors[type];
const header = `${chalk[color](`[${this.date}][${shard ? `shard${this._shardId(shard)}` : 'manager'}]`)}`;
this.logger.log(type, `${header} : ${string}`);
}
//Messages coming from the shards process.send functions.
_handleMessage(shard, message) {
this.write(message.type, message.message, shard);
}
_shardId(shard) {
const id = shard.id;
return `${id}`.length === 1 ? `0${id}` : `${id}`;
}
get date() {
return moment().format("MM-DD-YYYY hh:mm:ss");
}
}
module.exports = Logger;
const Constants = {
Colors: {
error: 'red',
warn: 'yellow',
info: 'blue',
verbose: 'cyan',
debug: 'magenta',
silly: 'magentaBright'
}
};