-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.js
51 lines (43 loc) · 2.13 KB
/
logger.js
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
const fs = require('fs');
const path = require('path');
const { EmbedBuilder } = require('discord.js');
const moment = require('moment');
require('dotenv').config();
const Log = require('./schemas/Log');
const logFilePath = path.join(__dirname, 'bot.log.json');
async function logToDiscordChannel(client, details) {
const logsChannelId = process.env.LOGS_CHANNEL_ID;
if (!logsChannelId) return;
const channel = await client.channels.fetch(logsChannelId).catch(console.error);
if (!channel) return;
const embedColor = process.env.EMBED_COLOR || '#0099FF';
const embed = new EmbedBuilder()
.setColor(embedColor)
.setTitle(`${details.action} Log`)
.setTimestamp();
if (details.targetId) embed.addFields({ name: 'Target', value: `<@${details.targetId}>` });
if (details.executorId) embed.addFields({ name: 'Executor', value: `<@${details.executorId}>` });
if (details.reason) embed.addFields({ name: 'Reason', value: details.reason });
if (details.messageContent) embed.addFields({ name: 'Content', value: details.messageContent });
if (details.imageUrl) embed.setImage(details.imageUrl);
if (details.duration) embed.addFields({ name: 'Duration', value: `${details.duration} minutes` });
await channel.send({ embeds: [embed] }).catch(console.error);
}
function logger(client, details) {
if (details.level === 'warn' || details.level === 'error') {
console[details.level](`${details.action}: ${details.message}`);
} else {
if (process.env.LOGGING_METHOD === 'mongodb') {
const logEntry = new Log({ ...details, timestamp: new Date() });
logEntry.save().catch(error => console.error('Error saving log to MongoDB', error));
} else if (process.env.LOGGING_METHOD === 'channel') {
logToDiscordChannel(client, details);
} else {
const logEntry = JSON.stringify({ ...details, timestamp: new Date().toISOString() }) + "\n";
fs.appendFile(logFilePath, logEntry, err => {
if (err) console.error('Error appending log to file', err);
});
}
}
}
module.exports = logger;