-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogger.js
More file actions
86 lines (67 loc) · 1.95 KB
/
logger.js
File metadata and controls
86 lines (67 loc) · 1.95 KB
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
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const FormData = require('form-data');
dotenv.config();
const LOG_LEVELS = {
INFO: 'info',
WARN: 'warn',
ERROR: 'error',
};
const COLORS = {
INFO: '\x1b[32m', // Green
WARN: '\x1b[33m', // Yellow
ERROR: '\x1b[31m', // Red
RESET: '\x1b[0m', // Reset color
};
const LOG_QUEUE = [];
let IS_LOGGING = false;
const LOGS_FOLDER = path.join(__dirname, 'logs');
// Ensure the logs folder exists
if (!fs.existsSync(LOGS_FOLDER)) {
fs.mkdirSync(LOGS_FOLDER);
}
const getCurrentDate = () => {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
const getLogFilePath = () => {
const currentDate = getCurrentDate();
return path.join(LOGS_FOLDER, `${currentDate}.log`);
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const logToConsole = (level, message) => {
const color = COLORS[level.toUpperCase()] || '';
console.log(`${color}[${level.toUpperCase()}]${COLORS.RESET} ${message}`);
};
const logToFile = (filePath, message) => {
fs.appendFile(filePath, `${message}\n`, (err) => {
if (err) {
console.error('Error appending to log file:', err);
}
});
};
const processLogQueue = async () => {
IS_LOGGING = true;
while (LOG_QUEUE.length > 0) {
const { level, message } = LOG_QUEUE.shift();
logToConsole(level, message);
const logFilePath = getLogFilePath();
logToFile(logFilePath, `[${level.toUpperCase()}] ${message}`);
}
IS_LOGGING = false;
};
const log = (level, message) => {
LOG_QUEUE.push({ level, message });
if (!IS_LOGGING) {
processLogQueue();
}
};
module.exports = {
info: (message) => log(LOG_LEVELS.INFO, message),
warn: (message) => log(LOG_LEVELS.WARN, message),
error: (message) => log(LOG_LEVELS.ERROR, message),
};